do you master list comprehensions?

Peter Otten __peter__ at web.de
Mon Dec 13 16:08:32 EST 2004


Will Stuyvesant wrote:

>>>> data = [['foo','bar','baz'],['my','your'],['holy','grail']]
>>>> result = []
>>>> for d in data:
> ...     for w in d:
> ...        result.append(w)
>>>> print result
> ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
> 
> puts all the words in a list, like I want.
> 
> How to do this with [lc] instead of for-loops?

>>> data = [['foo','bar','baz'],['my','your'],['holy','grail']]
>>> [w for d in data for w in d]
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']

See how the for expressions in the list comprehension exactly match your
nested for loops? That's all there is to it.

Peter




More information about the Python-list mailing list