flattening lists

dn PythonList at DancesWithMice.info
Tue Oct 11 17:08:07 EDT 2022


On 12/10/2022 08.32, SquidBits _ wrote:
> Does anyone else think there should be a flatten () function, which just turns a multi-dimensional list into a one-dimensional list in the order it's in. e.g.
> 
> [[1,2,3],[4,5,6,7],[8,9]] becomes [1,2,3,4,5,6,7,8,9].
> 
> I have had to flatten lists quite a few times and it's quite tedious to type out. It feels like this should be something built in to python, anyone else think this way?


There is a flatten function!

First though, are we ONLY talking about 'flattening' a 2D list (per 
example, above) or might the requirements extend to multiple-dimensions? 
The solutions vary accordingly!


Two-dimensions:
(don't think this method previously-mentioned, but very readable)

 >>> l = [[1,2,3],[4,5,6,7],[8,9]]
 >>> flattened = list()
 >>> for element in l:
...     flattened += element
...
 >>> flattened
[1, 2, 3, 4, 5, 6, 7, 8, 9]

(NB if "l" were three-dimensional, "flattened" would become 2D)


Multi-dimensional:
Reach for itertools:
(https://docs.python.org/3/library/itertools.html#itertools.chain)

 >>> import itertools as it
 >>> iter_flattened = it.chain( *l )
 >>> list( iter_flattened )
[1, 2, 3, 4, 5, 6, 7, 8, 9]


Wrt "I have had to flatten lists quite a few times and it's quite 
tedious to type out.", isn't this a "code-smell"?

Certainly motivation to generalise and write a solution as a function. 
Do it once, and do it right!

Hence advice elsewhere to build a list-processing utility-library.

On the other hand, has it already been done for us?


An exercise for the reader:
is reaching for itertools 'over-kill' in 2D?
- speed-comparison between loading the itertools library and then 
employing the speedy method, or using a (built-in) for-loop at 
Python-speed with no import-overhead?
(results will vary significantly according to len( l ), but do they 
remain consistently in-favor or one method or the other?)
-- 
Regards,
=dn


More information about the Python-list mailing list