do you master list comprehensions?

Steven Bethard steven.bethard at gmail.com
Mon Dec 13 16:09:00 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']
> 

Take advantage of the fact that you can have more than one 'for' in a 
list comprehension:

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

Steve



More information about the Python-list mailing list