Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
Chris Angelico
rosuav at gmail.com
Sat Mar 22 00:51:13 EDT 2014
On Sat, Mar 22, 2014 at 3:39 PM, Rustom Mody <rustompmody at gmail.com> wrote:
>> So if that's not going to be broken, how is this fundamentally different?
>
>> def func_loop():
>> for x in 1,2,3:
>> yield (lambda: x)
>
> Thats using a for-loop
> A 'for' in a comprehension carries a different intention, the matching names
> being merely coincidental.
So what you're saying is that these two are fundamentally different:
def unrolled():
x = 1
yield (lambda: x)
x = 2
yield (lambda: x)
x = 3
yield (lambda: x)
def loop():
for x in 1,2,3:
yield (lambda: x)
In other words, a loop should be implemented as a separate binding
each time, not a rebinding. That's an interesting point, and it does
make some sense; effectively, what you want is for the body of a for
loop to be a new scope, a unique scope every iteration of the loop,
and one that automatically closes over all variables in the parent
scope (including for assignments) except for the loop
iteration/counter variable.
That does make some sense, but it doesn't really fit Python's concept.
It would, however, fit a more C-like language, where locals are
declared (in Python, you'd have to put a whole lot of implicit
'nonlocal' statements at the top of the loop).
ChrisAg
More information about the Python-list
mailing list