r/PythonLearning • • 3d ago

Help Request Why does my loop skip items after I remove them?

I'm trying to remove all the even numbers from a list while looping over it. Here's what I wrote:

nums = [2, 4, 6, 8]

for x in nums:
    if x % 2 == 0:
        nums.remove(x)

print(nums)

The output is [4, 8]. I expected [] since every number in the list is even. Some of them just stay in there.

I tried looping over a copy instead, for x in nums[:]:, and that gives [] like I wanted. But I don't really get why the first version skips 4 and 6. I guess the list changes size while the loop runs, but I can't picture what the loop is doing on each pass.

Why does the loop skip 4 after removing 2?

5 Upvotes

12 comments sorted by

•

u/Sea-Ad7805 2d ago

Run program above by clicking Memory Graph Web Debugger and see its state change step by step.

2

u/apnorton 3d ago

Mutating a list while iterating over it is going to produce screwy/unintuitive results. Usually the general advice is "don't do that." 😛

What's likely happening is that removing the item deletes 2 from the list, so the iterator internally points to the 4... and then the iterator advances so the second iteration is pointing at 6.

2

u/baubleglue 2d ago

Don't saw off the branch you are sitting on.

1

u/Orgasml 3d ago

It goes through 4 indices (0,1,2 3): 1st loop checks nums[0] and finds 2 and deletes it. This makes your new list [4,6,8], which puts 4 at index 0.

2nd loop it checks num[1] which is now 6 and deletes it making your new list [4,8]

Then it checks num[2] which doesn't exist anymore and the same with num[3]. Thus you end up with [4,8]

When you use nums[:] it creates a temporary copy, which allows it to work as expected.

1

u/notyboy01 3d ago

Think of it like people standing in a numbered line. You tell person number one to leave so everyone steps forward one space. Next you look at spot number two and completely skip the person who just moved into spot number one.

1

u/BenicioZabala 3d ago

The for loop walks the list by index, not by value. It keeps a hidden position counter that goes 0, 1, 2... and each pass grabs whatever is at that position right now.

Pass 1: index 0 is 2, you remove it, list becomes [4, 6, 8]. Pass 2: the counter moves to index 1, which is now 6 (4 slid into index 0 and got jumped over). You remove 6, list is [4, 8]. Pass 3: index 2 doesn't exist anymore, so the loop ends. That's why 4 and 8 are left.

Looping over a copy works because the copy never changes, so every item gets visited. The more common way is a list comprehension that builds a new list:

nums = [x for x in nums if x % 2 != 0]

Or if you need to change it in place, use nums[:] = [x for x in nums if x % 2 != 0].

1

u/Sykander- 2d ago

On the first loop x is 2 and passes x % 2 == 0 so x is removed from nums, then the list updates and now has a different ordering

On the second loop it moves to x = 6 now (because 4 is now at position 0 and your loop has gone to position 1)

1

u/OfAnOldRepublic 1d ago

u/Orgasml has a great answer regarding what's happening.

In terms of a better solution, rather than truncating the list you're iterating over, start by creating an empty array, and then only add elements from the original list if they do NOT pass the test (or, rewrite the test to define what to add).

Then, depending on the purpose of the truncation, you can either replace the original list with the truncated copy, or use the copy as your new primary.

1

u/Naive_Programmer_232 11h ago edited 11h ago

you're modifying the thing you're looping over in-place. so remember when iterating over an object, even if you express the iteration variable as direct reference to the element, behind the scenes the index is being tracked. ex:

 1st iteration:
 index: 0
 nums (before): [2,4,6,8]
 x: 2
 x%2==0: True
 nums (after): [4,6,8]

 2nd iteration:
 index: 1
 nums (before): [4,6,8]
 x: 6
 x%2==0: True
 nums (after): [4,8]

 3rd iteration: (attempt)
 index: 2 
 nums (before): [4,8]
 ...
 IndexError: loop index 2 is out of range since nums=[4,8] (max index=1)

 so you're left with [4,8] 

in this case if you want to remove them all, you need the index to decrement to avoid the out range error, this could be done by going backward:

nums=[2,4,6,8]
for index in range(len(nums)-1,-1,-1):
    x=nums[index]
    if x%2==0:
       nums.remove(x)

1st iteration:
index: 3
nums (before): [2,4,6,8]
x: 8
x%2==0: True
nums (after): [2,4,6]

2nd iteration:
index: 2
nums (before): [2,4,6]
x: 6
x%2==0: True
nums (after): [2,4]

3rd iteration:
index: 1
nums (before): [2,4]
x: 4
x%2==0: True
nums (after): [2]

4th iteration:
index: 0
nums (before): [2]
x: 2
x%2==0: True
nums (after): []

StopIteration -> loop ends -> nums=[]

hopefully that makes sense.

1

u/Due-Mortgage-6854 11h ago

Your loop skips items because Python tracks list iteration by hidden index positions (0, 1, 2...), not by item values. When you remove an item, all remaining elements shift to the left into earlier indices while the loop still advances its internal counter forward.

Change Line 3 to


for x in nums[:]:
    if x % 2 == 0:
        nums.remove(x)

1

u/Educational-Paper-75 3d ago

Don't iterate and delete in forward direction!

-1

u/StephenHawkinguss 2d ago

Ask AI. Don't waste time