MMMMMCCLXXVII MMMMMCCLXXVII - 1 month ago 7
Python Question

fors in python list comprehension

Consider I have nested for loop in python list comprehension

>>> data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]


I can't explain why is that when i change the order of two
fors


for y in x


What's
x
in second list comprehension?

Answer

It's holding the value of the previous comprehsension. Try inverting them, you'll get an error

>>> data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> [y for y in x for x in data]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

To further test it out, print x and see

>>> [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> x
[6, 7, 8]
>>> [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]