-2
votes

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))
1
VTR since OP there is asking why Python doesn't have block scope. Instead could be a duplicate of Block scope in Python and/or Short description of the scoping rules? - wjandrea

1 Answers

4
votes

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