Recursive list comprehension

Peter Otten __peter__ at web.de
Mon Dec 6 04:40:42 EST 2004


Timothy Babytch wrote:

> Hi all.
> 
> I have a list that looks like [['N', 'F'], ['E'], ['D']]
> I try to make it flat one: ['N', 'F', 'E', 'D']
> 
> How can I archieve such an effect with list comprehension?
> Two cycles did the job, but that way did not look pythonic..
> 
> I tried
> print [x for x in y for y in c_vars]
> and got NameError: name 'y' is not defined.
> 

The order of the for expressions is as it would be for nested loops:

>>> items = [['N', 'F'], ['E'], ['D']]
>>> [y for x in items for y in x]
['N', 'F', 'E', 'D']

I would still prefer a for loop because it spares you from iterating over
the sublist items in python:

>>> data = []
>>> for sub in [['N', 'F'], ['E'], ['D']]:
...     data.extend(sub)
...
>>> data
['N', 'F', 'E', 'D']

Peter




More information about the Python-list mailing list