[Tutor] Flattening multi-dimentional list

Kent Johnson kent37 at tds.net
Thu Sep 29 05:17:59 CEST 2005


Bernard Lebel wrote:
> Hello,
> 
> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?

If the list is just nested one deep and every element is a tuple then a single list comprehension will do it:

 >>> l=[(1,2), (3,4)]
 >>> [ x for t in l for x in t ]
[1, 2, 3, 4]

Kent



More information about the Tutor mailing list