Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list.pop inside a for loop doesn't pop the last elements

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading