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 16:54:00 EDT 2014


On Saturday, March 22, 2014 2:12:53 AM UTC+5:30, vasudevram wrote:
> Hi list,

> Can anyone - maybe one of the Python language core team, or someone with knowledge of the internals of Python - can explain why this code works, and whether the different occurrences of the name x in the expression, are in different scopes or not? :

> x = [[1,2], [3,4], [5,6]]
>     [x for x in x for x in x]

> I saw this on a Hacker News thread about Python, and here is a post I wrote that gives more details about it, including relevant links, how I found that it can be extended to a triply-nested list, and my thoughts about the scope issue:

> http://jugad2.blogspot.in/2014/03/flatten-list-of-lists-with-list.html

> A few people commented about it, both on my blog, and on the Python Reddit where I also submitted my post, but I'm not sure I'm convinced of their reasoning or understand it, hence posting the question here.

Lets try without comprehending comprehensions :-) 

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



More information about the Python-list mailing list