0
items = [10, 5, -2, 23, 5, 6,7]

For i in items:
    if i <= 5:
       items.remove(i)
print(items)

Does anybody know why -2 is not taken into account in for loop? It works if the condition is i < 5 but -2 is passed over when the condition is <=

Mushif Ali Nawaz
  • 3,707
  • 3
  • 18
  • 31
  • 5
    Never change the object you are iterating. It causes problems. – Aryerez Aug 15 '21 at 11:07
  • 2
    Categorically, it’s a bad idea (yields unexpected results) to iterate over an iterable which is being edited. Make a copy of (or create a new) output list. This should address the issue. (Basically, -2 is being skipped) – S3DEV Aug 15 '21 at 11:07
  • 3
    Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Ture Pålsson Aug 15 '21 at 11:08

2 Answers2

2

The answer is quite simple. If you change the object you are working with, it will restructure automatically. What is happening is the following:

Your starting list -> [10, 5, -2, 23, 5, 6, 7]

Step 0. First iteration of the loop (checks the first element of the list) -> 10 <= 5 False

Step 1. Second iteration of the loop (checks the second item in the list) -> 5 <= 5 True

Your current list -> [10, -2, 23, 5, 6, 7]

Step 2. Third iteration of the loop (checks the third item in the list) -> 23 <= 5 False

As you can see, when you removed the number 5, the -2 became the second item in the list. However, the for loop does not know this, and it will continue to search with the next values ​​thinking that it has already checked for -2, since it is now the second value in the list.

This is why it is not recommended to change objects while iterating with them.

0

Try to filter the list and create a new one.

numbers= [10, 5, -2, 23, 5, 6,7]
positive_numbers = [x for x in numbers if x > 0]
balderman
  • 22,927
  • 7
  • 34
  • 52