[Python-Dev] Iteration variables and list comprehensions

Tim Peters tim.one@home.com
Wed, 30 May 2001 16:07:37 -0400


[Tim]
> Note that "the iterator variables" needn't be bare names:

[Fred]
>   I didn't realize this either.

You have to get your head out of the docs and read more code <wink>.

> I'm quite surprised by it, in fact, though I understand (I think) why
> it works that way.  But was this intentional?

I expect so.

> It seems like pure evil to me!

Sometimes it's the bee's knees; for example,

>>> digits = range(3)
>>> x = [None] * 3
>>> base3 = [x[:] for x[0] in digits for x[1] in digits for x[2] in digits]
>>> base3
[[0, 0, 0], [0, 0, 1], [0, 0, 2],
 [0, 1, 0], [0, 1, 1], [0, 1, 2],
 [0, 2, 0], [0, 2, 1], [0, 2, 2],
 [1, 0, 0], [1, 0, 1], [1, 0, 2],
 [1, 1, 0], [1, 1, 1], [1, 1, 2],
 [1, 2, 0], [1, 2, 1], [1, 2, 2],
 [2, 0, 0], [2, 0, 1], [2, 0, 2],
 [2, 1, 0], [2, 1, 1], [2, 1, 2],
 [2, 2, 0], [2, 2, 1], [2, 2, 2]]
>>>

I've done stuff "like that" often, albeit via the nested-loop spelling.

> I'd only expect it to support bare names and sequence unpacking (with
> only bare names at the "edge" of all nested unpackings).

It's too late to take it away now!  Python always worked this way.  And it's
really got nothing to do with what implementing what David wants (e.g., the
lambda transformation I mentioned preserves its semantics) -- apart from (I
hope) driving home that changes need to be considered very carefully.