flatten a level one list

Raymond Hettinger python at rcn.com
Thu Jan 12 06:44:43 EST 2006


[Robin Becker]
> Is there some smart/fast way to flatten a level one list using the
> latest iterator/generator idioms.
>
> The problem arises in coneverting lists of (x,y) coordinates into a
> single list of coordinates eg
>
> f([(x0,y0),(x1,y1),....]) --> [x0,y0,x1,y1,....]

Here's one way:

>>> d = [('x0','y0'), ('x1','y1'), ('x2','y2'), ('x3', 'y3')]
>>> list(chain(*d))
['x0', 'y0', 'x1', 'y1', 'x2', 'y2', 'x3', 'y3']

FWIW, if you're into working out puzzles, there's no end of interesting
iterator algebra tricks. Here are a few identities for your
entertainment:

# Given s (any sequence) and n (a non-negative integer):
assert zip(*izip(*tee(s,n))) == [tuple(s)]*n
assert list(chain(*tee(s,n))) == list(s)*n
assert map(itemgetter(0),groupby(sorted(s))) == sorted(set(s))


Raymond




More information about the Python-list mailing list