CODE :
stack = ['BOB','TOM','JAI','ALI','OM']
print(stack)
for i in stack:
stack.pop()
print(stack)
OUTPUT :
['BOB', 'TOM', 'JAI', 'ALI', 'OM']
['BOB', 'TOM']
why does it stop after popping the last 3 elements? the list still has 2 elements left but it doesnt work for some reason
>Solution :
That’s because you modified the list while you are iterating over it.
If first iteration, Python gets the item at index 0 of the list,
If second iteration, Python gets the item at index 1 of the list,
etc.
The implicit counter variable that Python uses for getting items is incrementing…
Print your list in every iteration to see what is in it:
stack = ['BOB', 'TOM', 'JAI', 'ALI', 'OM']
for i in stack:
print(stack)
stack.pop()
print(stack)
output:
['BOB', 'TOM', 'JAI', 'ALI', 'OM']
['BOB', 'TOM', 'JAI', 'ALI']
['BOB', 'TOM', 'JAI']
['BOB', 'TOM']
so :
In first iteration --> idx = 0 --> ['BOB', 'TOM', 'JAI', 'ALI', 'OM']
In second iteration --> idx = 1 --> ['BOB', 'TOM', 'JAI', 'ALI']
In third iteration --> idx = 2 --> ['BOB', 'TOM', 'JAI']
In forth iteration --> idx = 3 --> ['BOB', 'TOM'] --> Exit the loop here.
Solution:
for i in stack.copy(): # Now you are iterating over a "copy" of the list
stack.pop()
You could also do:
for _ in range(len(stack)):
stack.pop()