do you master list comprehensions?

Will Stuyvesant hwlgw at hotmail.com
Mon Dec 13 15:51:25 EST 2004


Here is a question about list comprehensions [lc].  The
question is dumb because I can do without [lc]; but I am
posing the question because I am curious.

This:

>>> 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?

I tried funnies like [[w for w in L] for L in data],
that is correct syntax, but you'd never guess.

I know, silly!  No need for [lc]!  So there's my
question.  I am sure a one-liner using [lc] will be very
enlightening.  Like studying LISP.


--
I wish there was a knob on the TV to turn up the intelligence.
There's a knob called `brightness', but it doesn't work.
-- Gallagher




More information about the Python-list mailing list