Mr.Ulis
Mr.Ulis

Reputation: 157

Why does my loop not iterate the whole length?

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

Answers (2)

Roberto Caboni
Roberto Caboni

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:

  1. First iteration. x is 1, [1,2,3,4,5,6,7,8,9] is printed, element 2 is removed
  2. Second iteration. x is 3, [1,3,4,5,6,7,8,9] is printed, element 3 is removed
  3. Third iteration. x is 5, [1,4,5,6,7,8,9] is printed, element 4 is removed
  4. Fourth iteration. x is 7, [1,5,6,7,8,9] is printed, element 6 is removed
  5. Fifth iteration. x is 9, [1,6,7,8,9] is printed, element 5 is removed
  6. The loop ends because there's nothing more to iterate on.

Note how modifiying the array within the loop caused an unexpected sequence of items.

Upvotes: 2

Guy_g23
Guy_g23

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

Related Questions