1

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

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.