4

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
MMMMMCCLXXVII
  • 571
  • 1
  • 8
  • 23
  • Maybe it's worth pointing out that this discrepancy doesn't happen in `ipython` terminal though. Any ideas why? – kmario23 Apr 23 '17 at 23:02

2 Answers2

6

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]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • OH,I SEE !! `[y for y in x for x in data]` So the nested `x` won't change the value of outer `x` , in another way , `for x in data` is not working. Am I right? But wouldn't the result be `[6,7,8]`? – MMMMMCCLXXVII Oct 08 '16 at 15:43
  • @MMMMMCCLXXVII I'm not sure if I follow. The list comprehension does not provide a new scope. See [this](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules). – Bhargav Rao Oct 08 '16 at 15:47
3

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]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126