3

When I use List.pop inside a for loop that uses enumerate, the process terminates before getting to the end of the list. How do I get around having pop cut short the process?

I've checked that if I write the loop using pop but without enumerate, then it works as expected. Likewise, if I remove pop and use enumerate to do something else, it also works as expected.

Here is the code:

x=[0,2,4,6,8,10] 
for i in enumerate(x):
x.pop(0)
print(x)

I expect to have the following printed:

[2,4,6,8,10]
[4,6,8,10]
[6,8,10]
[8,10]
[10]
[]

Instead, I receive

[2,4,6,8,10]
[4,6,8,10]
[6,8,10]

If I run it again then I receive

[8,10]
[10]

and if I run it again I receive

[]

1 Answer 1

2

Use range

Ex:

x=[0,2,4,6,8,10] 
for i in range(len(x)):
    x.pop(0)
    print(x)

Output:

[2, 4, 6, 8, 10]
[4, 6, 8, 10]
[6, 8, 10]
[8, 10]
[10]
[]

Note: Modifying a list while iterating it is not good practice.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering. Can you explain why len(x) isn't also problematic sense x is getting modified? I'm Ok with using the version you suggest, but I'd like to understand why the enumerate version doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.