1

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

PsyQuake
  • 45
  • 8
  • You should not modify the list while you are iterating over it. – S.B Feb 05 '22 at 10:35
  • @SorousHBakhtiary Is correct. You can loop over `range(len(stack))` instead to get the desired behavior. – I Dav Feb 05 '22 at 10:37

1 Answers1

2

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()
S.B
  • 13,077
  • 10
  • 22
  • 49
  • 1
    Since the element is not used in the loop, the copy is not necessary. looping over `range(len(stack))` is more efficient. – I Dav Feb 05 '22 at 10:40
  • okay thanks! i guess thats just how python works but im just curious why the false loops occur when the container is being altered when we are iterating through it? – PsyQuake Feb 05 '22 at 10:49
  • @PsyQuake I wrote an answer to another question [here](https://stackoverflow.com/a/64842523/13944524), but I think you will get your answer why. That `index` variable is independent of the loop's workflow. – S.B Feb 05 '22 at 10:53
  • @SorousHBakhtiary i see – PsyQuake Feb 05 '22 at 10:57