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

Rustom Mody rustompmody at gmail.com
Fri Mar 21 17:09:19 EDT 2014


On Saturday, March 22, 2014 2:26:09 AM UTC+5:30, vasudevram wrote:
> On Saturday, March 22, 2014 2:24:00 AM UTC+5:30, Rustom Mody wrote:
> > Lets try without comprehending comprehensions :-) 
> > >>> x=[[1,2],[3,4]]
> > >>> for x in x:
> > ...   for x in x:
> > ...      print x
> > ... 
> > 1
> > 2
> > 3
> > 4

> Nice and all, thanks, but doesn't answer the question.

Which is?



A 'for' introduces a scope:

>>> 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

And so we can do:

>>> x = [1,2,3]
>>> for x in x:
...   print x
... 
1
2
3

which implies that in a "for var in exp: ..."
the exp is evaluated in outer scope whereas the var has a new scope inside
the "..."

Now repeatedly apply that principle to the nested for.
Same principle for nested for in a comprehension.



More information about the Python-list mailing list