Take the 2-minute tour ×

Possible Duplicate:
join list of lists in python
Flatten (an irregular) list of lists in Python
How can I flatten lists without splitting strings?

I have a list-tuple-list tree and I'd like to flatten it for a query, so that I can print all the items of the the first lists of each tuple.

I can do it via a for loop

bigNest = [([item1,item2],[]),([item3],[item4])]
mergedlist = []
for listItem in bigNest:
   mergedlist += listItem[0]
print mergedList

I'm wondering if there's a simpler/quicker way which will also work with larger tuples.

share|improve this question
Have you done a search for "flatten"? This has been answered 100 times. –  Mark Ransom Nov 30 '12 at 17:45
There are a lot of different ways to do, as discussed in the previous answers (which is why I'm voting to close). There's terse but slow (sum(nested_list, [])) or the various itertools-based solutions (e.g. itertools.chain) which will scale up considerably better. –  Joe Kington Nov 30 '12 at 17:50
I did actually search but I obviously didn't hit the right keywords because none of the topics above came up –  Db0 Nov 30 '12 at 17:53
Also, sorry but none of the "possible duplicates" above answer my question. I know how to flatten if I want to. I want the pythonic way to do it. The ones listed are all bigger than mine! –  Db0 Nov 30 '12 at 17:56
print list(chain.from_iterable(item for item in chain.from_iterable(bigNest) if item)) –  Pyson Nov 30 '12 at 18:01
show 6 more comments

marked as duplicate by Joe Kington, JBernardo, Martijn Pieters, Steven Rumbalski, Jon Clements Nov 30 '12 at 17:51


1 Answer

edit: sorry the last post was wrong, you could do a list comprehension:

mergedlist = []
foovar = [mergedlist.extend(i[0]) for i in bigNest]
share|improve this answer
Can I simply throw that into a print? I.e. can I print [mergedlist.extend(i) for i in bigNest]? –  Db0 Nov 30 '12 at 17:57
Also, won't that extend my list by just adding the tuples? I need to go deeper. –  Db0 Nov 30 '12 at 18:05
oh yes, sorry, I meant .extend(i[0]) –  Cameron Sparr Nov 30 '12 at 19:04
add comment
