Reputation: 165
I have a problem understanding a nested list comprehension structure.
I have a list
>>> test
[[1, 2, 3], [4, 5], [6, 7, 8]]
If I do
t2=[]
for x in test:
for y in x:
t2.append(y)
then it returns
>>> t2
[1, 2, 3, 4, 5, 6, 7, 8]
which is exactly what I want. But WHY can't I do
t3=[y for y in x for x in test]
This gives me
>>> t3
[6, 6, 6, 7, 7, 7, 8, 8, 8]
Can anybody explain to me why t3 is not the same as t2? How ca I write a list comprehension expression that gives me the same as t2? Thank you very much for your help!
Upvotes: 2
Views: 506
Reputation: 104102
Just making sure you know about itertools chain:
>>> test=[[1, 2, 3], [4, 5], [6, 7, 8]]
>>> from itertools import chain
>>> list(chain(*test))
[1, 2, 3, 4, 5, 6, 7, 8]
Upvotes: 0
Reputation: 39403
In your code, before starting, x = [6, 7, 8]
from your previous loop (as pointed out by jonsharpe).
Therefore, it unfolds as such:
for y in x:
for x in test:
t3.append(y)
x
in the first loop point to [6, 7, 8]
, and is later reassigned, but that does not change the reference that is used in the first loop. The result would be the same if the second x
had a distinct name.
Upvotes: 1
Reputation: 122157
You need to reverse the for
loops:
t3 = [y for x in test for y in x]
otherwise (if you don't run the multi-line version beforehand!) x
is undefined. Your code only ran on a fluke - x
was still what it was at the end of the previous for
loop, hence your results.
Upvotes: 0
Reputation:
The for ... in ...
clauses inside a list comprehension need to go in the same order as if they were normal for-loops:
>>> test = [[1, 2, 3], [4, 5], [6, 7, 8]]
>>> t3 = [y for x in test for y in x]
>>> t3
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
Upvotes: 3