flattening lists

David Lowry-Duda david at lowryduda.com
Tue Oct 11 16:02:55 EDT 2022


On Tue, Oct 11, 2022 at 12:32:23PM -0700, 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?

I typically don't mind things that are one liners, especially if the one 
liner is a list comprehension.


def flatten1(inlist):
     return [l for sublist in inlist for l in sublist]

givenlist = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
print(flatten1(givenlist))

def flatten2(inlist):
     return sum(inlist, [])

print(flatten2(givenlist))


Looking up "flatten" in python's source reveals the (not at all obvious 
to me as I don't use chain) alternative


import itertools
def flatten3(inlist):
     return list(itertools.chain.from_iterable)

print(flatten3(givenlist))


I notice that "flatten" appears many times in python's source. I didn't 
check how many times it's used with the same meaning, though.

- DLD


More information about the Python-list mailing list