-2

I don't understand how this is possible? Here I am using the value of i for the for loop, outside the for loop.

for i, kv in enumerate(bucket): 
    k, v = kv  
    if key == k:
        key_exists = True
        break 

#here is the issue...

if key_exists:
    bucket[i] = ((key, value))
    print(i)
else:
    bucket.append((key, value))
wjandrea
  • 16,334
  • 5
  • 30
  • 53
  • VTR since OP [there](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops) is asking *why* Python doesn't have block scope. Instead could be a duplicate of [Block scope in Python](https://stackoverflow.com/q/6167923/4518341) and/or [Short description of the scoping rules?](https://stackoverflow.com/q/291978/4518341) – wjandrea Feb 11 '20 at 05:49

1 Answers1

4

This is possible because Python does not have block scope. The variable assigned to in the for loop (i in your code) doesn't have its own narrower scope limited to just the for loop; it exists in the outer scope, so it remains available after the loop.

For example:

for i in range(10):
    pass

print(i) # prints 9

The same is true of any other assignment inside the loop. Here, the variable j is visible after the loop, for the same reason: the for loop block is not a separate, narrower scope.

for i in range(10):
    j = 17

print(j) # prints 17
kaya3
  • 31,244
  • 3
  • 32
  • 61