3

I have below code on list comprehension.

x = 2
y = 3

[x*y for x in range(x) for y in range(y)]

This is giving me below error

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    [x*y for x in range(x) for y in range(y)]
  File "<pyshell#35>", line 1, in <listcomp>
    [x*y for x in range(x) for y in range(y)]
UnboundLocalError: local variable 'y' referenced before assignment

However, below code works.

[x*y for x in range(x)]
[0, 5]

Is there any scoping rule for the second for loop in list comprehension?

I am using Python 3.6.

thatisvivek
  • 875
  • 1
  • 12
  • 30
  • @Chris_Rands: the possible duplicate post does not talk about UnboundLocalError and scoping rule for list comprehension. – thatisvivek Mar 03 '17 at 12:53

1 Answers1

2

Good question,however this code works well in Python2.x,and it will throw UnboundLocalError in Python3.x.

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since it assigns a new value to x, the compiler recognizes it as a local variable. Thus the earlier variable attempts to print the uninitialized local variable and an error results.

See more details from Why am I getting an UnboundLocalError when the variable has a value?.

McGrady
  • 10,869
  • 13
  • 47
  • 69
  • Ok that means for loop does have a local scope in list comprehension? As per my understanding for loop does not create any local scope when created at module level. – thatisvivek Mar 03 '17 at 13:27