[Tutor] flattening a list

jfouhy at paradise.net.nz jfouhy at paradise.net.nz
Wed Jan 12 05:24:08 CET 2005


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]

-- 
John.


More information about the Tutor mailing list