Reputation: 31
I'm trying to understand the logic here, why this code doesn't remove all elements in the list?
int_lst = [1, 2, 3, 4, 5, 6]
for i in int_lst:
int_lst.remove(i)
print(int_lst)
print(int_lst) #Output: [2, 4, 6]
Upvotes: 0
Views: 113
Reputation: 123
That happens because you are removing elements in the same list you are iterating through. You can easily fix it by avoiding this:
for i in list(int_lst):
int_lst.remove(i)
Upvotes: 0
Reputation: 530970
When you remove an element, everything after that element effectively moves back one place. But the iterator doesn't know that: it just advance the pointer to the next element, skipping what should have been the next value bound to i
.
In detail, i
starts at 1. You remove it, and now 2 is in the current position of the iterator. The iterator advances, and now 3 is in the current position and bound to i
.
In other words, every time you remove an element, you effectively advance the iterator, in addition to the explicit advancement the iterator will perform.
Upvotes: 1