Fors in python list comprehension

Consider what I am nesting in a loop in understanding a python list

>>> 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 this happens when I change the order of two fors

for y in x

What xis the second meaning of the list?

+4
source share
2 answers

It holds the value of the previous comprehsension. Try to invert them, you will get an error message

>>> 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

For further testing, print xand 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]
+6
source

List conventions:

[y for x in data for y in x]
[y for y in x for x in data]

A forloop conversion [y for y in x for x in data]:

for y in x:
    for x in data:
        y

x x , :

[6, 7, 8]
+2

Source: https://habr.com/ru/post/1657145/


All Articles