do you master list comprehensions?
fredrik at pythonware.com
Wed Dec 15 20:27:20 CET 2004
Matthew Moss wrote:
>> >>> data = [['foo','bar','baz'],['my','your'],['holy','grail']]
>> >>> [e for l in data for e in l]
>> ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
> Okay, I tried this in an interactive Python session and it works as
> stated. My question is, why? How is the interpreter parsing that list
> expression that it makes sense?
the language reference has the answer:
"... the elements of the new list are those that would be produced
by considering each of the 'for' or 'if' clauses a block, nesting
from left to right, and evaluating the expression to produce a list
element each time the innermost block is reached."
or, conceptually, the compiler strips off the expression, and then
inserts newlines, colons and indentation, and wraps the expression
in an append statement.
[e for l in data for e in l]
result = 
for l in data:
for e in l:
except that it's an expression, and the result variable is hidden. (and
the compiler and the runtime is of course free to implement this in a
more efficient way)
More information about the Python-list