Tommy Fountain
Tommy Fountain

Reputation: 25

Python - Issue using list pop() method in loop

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?

Upvotes: 0

Views: 771

Answers (1)

user3483203
user3483203

Reputation: 51165

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.

Upvotes: 2

Related Questions