do you master list comprehensions?

Fredrik Lundh 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:

    http://www.python.org/doc/2.3.4/ref/lists.html

    "... 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.

so

    [e for l in data for e in l]

behaves like:

    result = []
    for l in data:
        for e in l:
            result.append(e)

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)

</F> 






More information about the Python-list mailing list