List comprehensions and evaluation of elements therein

Ian Kelly ian.g.kelly at gmail.com
Wed Sep 23 14:24:20 EDT 2015


On Wed, Sep 23, 2015 at 12:12 PM, James Harris <james.harris.1 at gmail.com> wrote:
> A list comprehension has various components. Anyone know when each of the
> elements is evaluated? In the form
>
>  [v0 for v0 in expr0 if expr1]
>
> If v0 appears in expr0 or expr1 the evaluation order matters.
>
> I think of the above as being a rewrite of
>
>  results = []
>  for v0 in expr0:
>    if expr1:
>      results.append(v0)
>  return results
>
> Further,
>
>  [v0, v2 for v0 in expr0 if expr1 for v2 in expr2 if expr3]
>
> leads to
>
>  results = []
>  for v0 in expr0:
>     if expr1:
>        for v2 in expr2:
>           if expr3:
>              results.append((v0, v2))
>  return results
>
> First of all, is that a correct analog of the list comprehension?

Looks right, see:
https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries

Note that the last sentence there about names not "leaking" is only
true for Python 3.

You may also be interested in PEPs 202 and 289.



More information about the Python-list mailing list