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

[]
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
fox-daniel
  • 59
  • 1
  • 3

1 Answers1

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.

Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • 1
    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. – fox-daniel Jul 20 '19 at 20:22