Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Mar 21 22:34:48 CET 2014


Rustom Mody wrote:

> A 'for' introduces a scope:

No, it doesn't!

>>>>x = 42
>>>>for x in [1,2,3]:
> ...   print x
> ... 
> 1
> 2
> 3
> 
> No sign of the 42 --v ie the outer x -- inside because of scope

You're right that there's no sign of the 42, but it's
*not* because of scope, as you'll see if you do one
more print:

 >>> print x
3

> And so we can do:
> 
> 
>>>>x = [1,2,3]
>>>>for x in x:
> ...   print x
> ... 
> 1
> 2
> 3

Again, if you print x after the loop has finished,
you'll find that it's no longer bound to the original
list. This is because Python's for-loop does *not*
introduce a new scope -- there's only one x, and
the for-loop is sharing it with the rest of the code.

The real question is why the for-loop works in *spite*
of this fact.

The answer is that the for-loop machinery keeps an
internal reference to the list being iterated over,
so once the loop has started, it doesn't matter what
x is bound to any more.

-- 
Greg



More information about the Python-list mailing list