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

S

Sergio Correia

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?
 
V

Virgil Dupras

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.
 
P

Paul Rubin

Sergio Correia said:
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)
?

I thought map/reduce were considered ok again, but the above runs
in quadratic time, not good.

I'd use:

eggs = list(itertools.chain(*spam))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top