Recursive list comprehension

Peter Otten __peter__ at web.de
Mon Dec 6 06:50:19 EST 2004


Nick Coghlan wrote:

> from itertools import chain
> n = [['N', 'F'], ['E'], ['D']]
> print [chain(*n)]

However, [generator] is not the same as list(generator):

>>> from itertools import chain
>>> n = [['N', 'F'], ['E'], ['D']]
>>> print [chain(*n)]
[<itertools.chain object at 0x402ac60c>]
>>> print list(chain(*n))
['N', 'F', 'E', 'D']

And with the star operator you are foregoing some laziness, usually an
important selling point for the iterator approach. Therefore:

>>> n = [['N', 'F'], ['E'], ['D']]
>>> lazyItems = (x for y in n for x in y)
>>> lazyItems.next()
'N'
>>> list(lazyItems)
['F', 'E', 'D']
>>>

Of course this makes most sense when you want to keep the original n anyway
_and_ can be sure it will not be mutated while you are still drawing items
from the lazyItems generator.

Peter




More information about the Python-list mailing list