Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
Mark H Harris
harrismh777 at gmail.com
Mon Mar 24 21:56:28 EDT 2014
On 3/22/14 3:59 PM, vasudevram wrote:
>
> Thanks to all those who answered.
>
> - Vasudev
I am wondering if the question was answered?
>>>>
>>>> x = [[1,2],[3,4],[5,6]]
>>>> import ast
>>>> ast.dump(ast.parse('[x for x in x for x in x]'))
>
> "Module(body=
>
> [Expr(value=ListComp(elt=Name(id='x', ctx=Load()),
>
> generators=
>
> [comprehension(target=Name(id='x', ctx=Store()), iter=Name(id='x', ctx=Load()), ifs=[]),
>
> comprehension(target=Name(id='x', ctx=Store()), iter=Name(id='x', ctx=Load()), ifs=[])]))])"
>>>>
This is really, I think, the answer to the OPs question. Knowing how
python is parsing the comprehension of comprehensions is important, yes?
Obviously each x is within a different scope, within a separate
iterator. This seems to unwind from right to left?
I didn't see any ast entries in the thread, so just wondering.
marcus
More information about the Python-list
mailing list