0
x = int(input())
y = int(input())
print([[x, y] for x in range(x) for y in range(y)])

above, whenever i use the iterator variable as x and y, 'its shows an error'

but when i change it to a and b, 'it works fine' see below

x = int(input())
y = int(input())
print([[a, b] for a in range(x) for b in range(y)]) #this is working fine

Can anyone tell me the reason behind that UnboundLocalError?

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
  • 2
    It seems unwise to use `x` for both the bound and the iteration variable of your range iterations. Similarly `y`. List comprehensions have a special internal scope, and you're trying to reference `x` and `y` and also assign to variables `x` and `y` with different meanings. – khelwood Apr 06 '21 at 10:42

1 Answers1

0

Problem is that you're "redeclaring" x in your list comprehension. This is what happens in a micro scale of events:

  1. x = int(input()). x is declared and assigned with user input.
  2. y = int(input()). y is declared and assigned with user input.
  3. for x. x is declared in a more local scope (inside the list comprehension), but not assigned.
  4. in range(x). The iteration is defined to occur within the result of range(x). Since x is currently not assigned to any value, your UnboundLocalError exception happens.

As you have already seen, the solution is simply using a different variable for the iteration.

Marc Sances
  • 2,402
  • 1
  • 19
  • 34