Flatten a two-level list --> one liner?

Virgil Dupras hardcoded.software at gmail.com
Wed Mar 7 19:34:27 EST 2007


On Mar 7, 7:14 pm, "Sergio Correia" <sergio.corr... at gmail.com> wrote:
> Hi,
>
> I'm looking for an easy way to flatten a two level list like this
>
> spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>
> Into something like
> eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>
> There are *no* special cases (no empty sub-lists).
>
> I have found two ways:
>
> 1) Accumulator
> eggs = []
> for x in eggs:
>        eggs.extend(x)
>
> 2) Reduce
> eggs = reduce(lambda x, y: x+y, spam)
>
> I feel the 1st way is too cumbersome (three lines), and although I
> like the 2nd way (except for the lambda part), I understand reduce is
> discouraged by Guido so I want to know if there is a "Better Way"(TM)
> ?
>
> Any ideas?
>
> Thanks,
> Sergio
>
> PS: Why does `sum` works only with numbers?

A search in the python group should get you all the details you need.

Quick answer: "sum(eggs, [])", but the "correct" way is to have a
flatten() function, with those 3 lines.




More information about the Python-list mailing list