[Tutor] flattening a list

Marilyn Davis marilyn at deliberate.com
Wed Jan 12 06:49:43 CET 2005


On Wed, 12 Jan 2005 jfouhy at paradise.net.nz wrote:

> Quoting Bill Kranec <billk at fastmail.fm>:
> 
> > I have a list of lists, for example [ [1,2] , [3,4] ], and I would like
> > to pass all the elements of that list as arguments to a function (for 
> > example the intersection of all list elements). Is there a command in 
> > regular Python to do this? I would like to avoid the hassle and speed 
> > hit of a loop to extract all the list elements.
> 
> I don't think so...
> 
> There is a recipe on activestate for a flatten function.
> 
> Or you could use a list comprehension:
> 
> >>> arr = zip(range(10), range(10, 20))
> >>> arr
> [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8,
> 18), (9, 19)]
> >>> [x for y in arr for x in y]
> [0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19]
> 

Nice.

And there's:

>>> arr = zip(range(10), range(10, 20))
>>> arr
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]
>>> reduce(lambda x,y:x+y, arr)
(0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19)
>>> 

> 

-- 



More information about the Tutor mailing list