Your code will remove half. Because when you use a for
loop, it will iterate over the elements. Now you remove elements at the other side of the list, so the two pointers will reach each other midway and so the loop will stop.
So you start with the list:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 12, 122]
#^
*(the caret shows where the for loop pointer is located), next you pop and advance the caret:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 12, 122]
# ^
and so on:
[4, 5, 6, 7, 8, 9, 10, 18, 12, 122]
# ^
[5, 6, 7, 8, 9, 10, 18, 12, 122]
# ^
[6, 7, 8, 9, 10, 18, 12, 122]
# ^
[7, 8, 9, 10, 18, 12, 122]
# ^
[8, 9, 10, 18, 12, 122]
# ^
Now the index pointer has reached a point out of the range so the loop terminates. But it has not iterated over all elements: since each time you pop an element, it has jumped two paces at once so to speak.
Some general advice about looping over lists:
You better do not modify the list while you iterate over it.
A better way to do this is:
for _ in range(len(numbers)):
a = numbers.pop(0)
print(numbers)
or, as @Matthias proposes:
while numbers:
a = numbers.pop(0)
print(numbers)
Since the bool(..)
of a list is true of it contains at least one element. So here each time we check whether there is at least still an element in numbers
.