2

I am trying to print a list, delete item 0 and then print the list again for all items in the list. This is very simple but it's not working as I expected.It stops short of completing the for loop for all of the list items.

I tried using the range function inside a list first with both the del and pop() methods. That did not work so I have been using a list and get the same results.

seals = [1,2,3,4,5,6,7,8,9]

for seal in seals:
    print(seals)
    seals.pop(0)

Expected Result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]

Actual Result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
mackie
  • 23
  • 4

2 Answers2

1

Python is funny here, so you have to be very clear to him :D :

seals = [1,2,3,4,5,6,7,8,9]

for seal in seals[:]:
    print(seals)
    seals.pop(0)

Or use range:

seals = [1,2,3,4,5,6,7,8,9]

for seal in range(len(seals)):
    print(seals)
    seals.pop(0)

Both reproduce:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

If your intention is to pop values off until there are no more, it's probably clearer to write that intention into the code with something like:

seals = [1,2,3,4,5,6,7,8,9]

while seals:
    print(seals)
    seals.pop(0) 

This avoids the problem of modifying the list while iterating the same list.

If you don't want to modify seals as you go, then you could do something like:

seals = [1,2,3,4,5,6,7,8,9]

for i, v in enumerate(seals):
    print(seals[i:])

seals remains unaltered at the end of this.

Mark
  • 90,562
  • 7
  • 108
  • 148