Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
MMMMMCCLXXVII Avatar asked Jan 05 '23 06:01

MMMMMCCLXXVII


1 Answers

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]
like image 167
Bhargav Rao Avatar answered Jan 13 '23 12:01

Bhargav Rao