0

I'm trying to modify a loop function that contains over a hundred lines of code.

If I have a loop in python that goes through a list, why does a for item in list: loop only finish half way through? Shouldn't it keep looping until all items are popped?

For example if I have this list:

 l1 = [1,2,3,4,5,6]


    for item in l1:
        l1.pop(0)
        print l1

No matter how many items the list contains, it will only finish when 50% of the list has been popped:

OUTPUT FOR CODE ABOVE:

[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]

Process finished with exit code 0

Can I still pop each item in the list without changing the for item in l1: loop?

user1504605
  • 579
  • 5
  • 19

1 Answers1

1

You could create a copy of the list and pop from the original one:

In [1]: l1 = [1,2,3,4,5,6]

In [2]: for item in l1[:]:
   ...:     l1.pop(0)
   ...:     print l1
   ...:     
[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]

However, this is certainly not elegant.

miku
  • 181,842
  • 47
  • 306
  • 310