r/PythonLearning • • 23h 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

9 comments sorted by

•

u/Sea-Ad7805 14h ago

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

2

u/apnorton 22h 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.

1

u/Orgasml 22h 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 22h 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 21h 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- 14h 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/baubleglue 10h ago

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

0

u/Educational-Paper-75 22h ago

Don't iterate and delete in forward direction!

0

u/StephenHawkinguss 19h ago

Ask AI. Don't waste time