You're modifying the list while you iterate over it. That means that the first time through the loop, I> 1
, so I>1
is removed from the list. Then the for loop goes to the third item in the list, which is not 3, but 4! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 4. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value
Check the visualization of what's happening
[1, 2, 3, 4, 5, 6]
^
[1, 3, 4, 5, 6]
^
[1, 3, 5, 6]
^
[1, 3, 5]
For this example i>1
condition meets element 2 and removes it but 3 replaces the 2nd position of 2. Thus 3 is getting a skip to remove. This way 5 also skip and the final output will be like
[1, 3, 5]
To avoid this way of removing you can set a condition to skip the element you need to remove and append the elements into a new list that you don't need to delete like:
ls = [i for i in a if i <= 1]
print(ls)