0

The following code:

list = ['A', 'B', 'C', 'D', 'E', 'F']

for item in list:
    removed_item = list.pop()
    print(removed_item + ' has been removed from the list')

print(list)

Gives the result:

F has been removed from the list
E has been removed from the list
D has been removed from the list
['A', 'B', 'C']

When I was expecting it to loop through the whole list and return and empty list. Why is it stopping half way through the list and leaving the A, B and C values in the list?

  • You are shortening the list while looping through it. – user3483203 Mar 11 '18 at 01:05
  • its usually not a good idea to modify the thing you are iterating on. Your loop starts at the beginning of the list, `pop` removes from the end of the list, and they meet in the middle. – avigil Mar 11 '18 at 01:38
  • Possible duplicate of [strange result when removing item from a list](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – Taku Mar 11 '18 at 01:43

1 Answers1

2

You are removing items from the end of your list while looping through it, so you will stop after 3 iterations. Instead, use a while loop here:

Also, do not name lists list, since you are reassigning the builtin list in python.

l = ['A', 'B', 'C', 'D', 'E', 'F']

while l:
    removed_item = l.pop()
    print(removed_item + ' has been removed from the list')

print(l)

Output:

F has been removed from the list
E has been removed from the list
D has been removed from the list
C has been removed from the list
B has been removed from the list
A has been removed from the list
[]

Here is a better explanation on why your previous method did not work:

You are looping through the list sequentially, so you will access A, B, C, D, E, F in that order, however, you are removing from the back of the list, so when you reach C, you are at the end of the list, since you have removed D, E, and F and the loop stops. Your method would work if you did the following:

for item in reversed(l):
    removed_item = l.pop()
    print(removed_item + ' has been removed from the list')

Since you would be looping from the end of the list, while removing from the end of the list.

user3483203
  • 50,081
  • 9
  • 65
  • 94
  • Still not clear on why exactly shortening the list would cause it to stop after 3 iterations when I have 6 items in the list. – Tommy Fountain Mar 11 '18 at 01:09
  • @TommyFountain added a better explanation – user3483203 Mar 11 '18 at 01:12
  • 1
    @TommyFountain Because the list iterator stops and raises StopIteration when the internal incremented index matches or exceeds the *current* length of the source. IE, when source[i] would raise IndexError. The source list is neither copied or frozen. – Terry Jan Reedy Mar 11 '18 at 01:48