List comprehensions and evaluation of elements therein
James Harris
james.harris.1 at gmail.com
Wed Sep 23 14:12:37 EDT 2015
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?
With this latter expansion the values of v0 and v2 could appear in expr4
or expr5. Again, the evaluation order would matter.
James
More information about the Python-list
mailing list