MMMMMCCLXXVII
MMMMMCCLXXVII

Reputation: 581

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?

Upvotes: 4

Views: 259

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

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]

Upvotes: 6

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48057

The list comprehensions are as:

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

A for loop conversion of [y for y in x for x in data] is:

for y in x:
    for x in data:
        y

Here x is holding the last updated value of x of your previous list comprehension which is:

[6, 7, 8]

Upvotes: 3

Related Questions