-1
a = [(1, 1), (35, 1), (1, 35), (35,35)]

for i in a:
    print(i)

then it prints

(1, 1)
(35, 1)
(1, 35)
(35, 35)

however this code , though I expected the same result

a = [(1, 1), (35, 1), (1, 35), (35,35)]

for i in a:
   a.remove(i)
   print(i)

then the result is

(1, 1)
(1, 35)

How can the method .remove make this difference? I have no idea how it works. Please help me!

Jasper
  • 11
  • 2
  • 2
    Never modify the list you're currently iterating over - the iterator won't notice that you've modified it, and have weird behavior like this. Always either iterate over a copy, or do the iteration and removal in two separate steps. See also https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating – Green Cloak Guy Sep 20 '21 at 13:26

1 Answers1

0

.remove makes a difference because you are updating the iterator as it interates.

Imagine i as a pointer which points to the 0th index of a and goes till the end of length(a).(Here, length(a) is itself changing).

So your code is like:

a = [1, 2, 3, 4]

for i in a:
    a.remove(i)
    print(i)

So internally , i is initialised to point to the 0th index of a in the first iteration.

In the next iteration, i is automatically initialised to point to the 1st index of a (if it exists)

In the next iteration, i is is automatically initialised to point to the 2nd index of a (if it exists) and so on...

So here is what happens in the loop:

Iteration 1

a = [1, 2, 3, 4]
i -> 0th index of a = 1

a.remove(i)
a -> [2, 3, 4]

print(i) -> prints 1

Iteration 2

a = [2, 3, 4]
i -> 1st index of a = 3

a.remove(i)
a -> [2, 4]

print(i) -> prints 3

Iteration 3

a = [2, 4]
i -> 2nd index of a = Does not exist -> Quit iteration 

Because of this, if you run the above program, only 1 and 3 will be printed.

Jdeep
  • 1,015
  • 1
  • 11
  • 19