numbers = [2,4, 6,8, 11, 23]
popped_numbers = []
for number in numbers:
i = numbers.pop(0)
print(i)
popped_numbers.append(i)
print(numbers)
results
2
4
6
[8, 11, 23]
numbers = [2,4, 6,8, 11, 23]
popped_numbers = []
for number in numbers:
i = numbers.pop(0)
print(i)
popped_numbers.append(i)
print(numbers)
results
2
4
6
[8, 11, 23]
It is because when you are poping from numbers
, then the size of it is actually changing. At the same time the iterator starts from 0
index in the array and increasing. So after picking the first 3 numbers, size of numbers
is equal to 3 and iterator is also 3 and the for loop breaks. You can implement it like this:
numbers = [2,4, 6,8, 11, 23]
popped_numbers = []
while len(numbers) > 0:
i = numbers.pop(0)
print(i)
popped_numbers.append(i)
print(numbers)
print(popped_numbers)
Because the pointer, when you pop an element from the numbers list in the loop, the pointer after the third iteration is in third element, at this point the last element in the list.
Like:
Iteration | element | list
__________|_________|_______
1 | 2 | [4,6,8,11,23]
2 | 4 | [6,8,11,23]
3 | 6 | [8,11,23]