Reputation: 157
This is the code:
r = [1,2,3,4,5,6,7,8,9]
for x in r:
print(r)
r.pop(1)
When I print(r)
, why does the print/loop stop after 5 iterations, and doesn't go the whole way?
Upvotes: 0
Views: 164
Reputation: 7490
The instruction r.pop(1)
removes the element of the array at index 1. Since the array has 9 elements, and just because you print it before removing again, you see 5 iterations.
In details:
x
is 1, [1,2,3,4,5,6,7,8,9]
is printed, element 2
is removedx
is 3, [1,3,4,5,6,7,8,9]
is printed, element 3
is removedx
is 5, [1,4,5,6,7,8,9]
is printed, element 4
is removedx
is 7, [1,5,6,7,8,9]
is printed, element 6
is removedx
is 9, [1,6,7,8,9]
is printed, element 5
is removedNote how modifiying the array within the loop caused an unexpected sequence of items.
Upvotes: 2
Reputation: 385
Because you are using r.pop(1)
which removes in every iteration the element at index 1 of the list r
, so you reach the list's end in the 5th iteration.
Note that in Python the indented block of a loop contains all commands that will be executed within that loop.
Upvotes: 2