Understanding remove() in a for loop

Hi everyone,

While I was studying I was doing an assignment that was about removing a value from a list.

But when it comes to a value that appears multiple times in a list, I tried to remove it with a for loop, which is actually not the right way of doing it because it wil cause to skip values because of the changing index.

my question is:
Do I understand the way this iteration / for loop works?

Let me show you my example.


#Remove all list items with value = 1
numbers = [1,1,5,6,56,1]

for x in numbers:
  if x  == 1:
    numbers.remove(1)

print(number)

#Output: [5, 6, 56, 1]

What is actually happening?

Start
[1, 1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

Iteration 1
Value on index 0 removed because it has value = 1
[1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

Iteration 2
For loop already did index 0 so it will skip the number 1, now next is index 1. 5 is not 1 so it will move to the left. Same for 6 and 56.

From

[1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

To
[5, 1, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

Iteration 3
[5, 6, 1, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

Iteration 4
[5, 6, 56, 1, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

Iteration 5
The value on index 4 is a 1 which will be removed.
[5, 6, 56, 1, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index

This is the end of the for loop.
The number 1 on the end of the list stays because it was skipped in the for loop, because the index 0 was already iterated.
[5, 6, 56, 1,] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index (index 5 does not exist anymore)

Hi @Wassenaar

Please check typos (number → numbers):

#Remove all list items with value = 1
numbers = [1,1,5,6,56,1]

for x in numbers:
  if x  == 1:
    numbers.remove(1)

print(numbers)

The code you’ve written will likely not work safely, and it can cause problems. The issue arises because you’re modifying the list (numbers.remove(1)) while iterating over it, which can lead to unexpected behavior.

The easiest fix is to iterate over a copy of the list:

# Iterate over a copy of the list
for x in numbers[:]:  # `numbers[:]` creates a copy of the list
    if x == 1:
        numbers.remove(1)

print(numbers)

Other methods:

while 1 in numbers:
    numbers.remove(1)
# Use list comprehension to remove all occurrences of 1
numbers = [x for x in numbers if x != 1]
1 Like

Problematic example:

numbers = [1,1,2,3,1,4]

for x in numbers:
  print(x)
  if x  == 1:
    numbers.remove(1)

numbers

gives:

1
2
3
1
[2, 3, 1, 4]