comprehensions was Re: Switch statements again
Tim Peters
tim.one at comcast.net
Fri Jan 17 10:28:28 EST 2003
[Ville Vainio]
> Of course, there is still the embarrassing issue of the list
> comprehension variable not being local to the list comprehension. Why,
> oh why won't people pre-deprecate it... at least in the documentation.
> Any hope to get it into the tutorial/lang reference for 2.3 :)?
[Erik Max Francis]
> Probably for the same reason that other iterative constructs that
> introduce variables don't make them local to that structure either:
>
> >>> [x for x in range(10)]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> >>> x
> 9
> >>> for y in range(10): print y,
> ...
> 0 1 2 3 4 5 6 7 8 9
> >>> y
> 9
That's right, and is really all there is to it. Guido wanted
[f(x) for x in whatever]
to act "exactly like"
result = []
for x in whatever:
result.append(f(x))
At the time, lexical nesting didn't yet exist in Python either. The case
for "magically local" bindings has gotten stronger since lexical nesting was
added, but now we've got a backwards compatibility burden too.
Note that the C-ish
if ((y = f(x) != whatever)
do something with y
can be simulated now via
if [y for y in [f(x)]][0] != whatever:
do something with y
as is. I hope to God nobody is doing that in real life, but then I never
expected anyone to do
(f() and [g()] or [h()])[0]
in real life either <0.5 wink>.
More information about the Python-list
mailing list