Issue with .remove on array

I'm guessing you're using pop in a loop ? Don't do it.
I didn't say anything about the code posted above that does it, because it breaks immediately after popping, but if you remove the break you're exposing yourself to issues like you're experiencing.

To understand why, let's take a simple example:

l = [2, 1, 3, 4, 6, 5, 7, 2, 8]

print l
for i, item in enumerate(l):
	print "index {}, item {}".format(i, item)
	if item % 2 == 0:
		l.pop(i)

print l

output:

[2, 1, 3, 4, 6, 5, 7, 2, 8]
index 0, item 2
index 1, item 3
index 2, item 4
index 3, item 5
index 4, item 7
index 5, item 2
[1, 3, 6, 5, 7, 8]

If you remove the item at index 0, the next item takes its place. So when you check at the next index... it's not what was 1 before, it's what was 2.

How to fix that ? Well, that depends on what you're trying to do.
In most cases, I'd suggest building a new list by filtering, ie:

l = filter(lambda item: item % 2, l)
# or
l = [item for item in l if item % 2]
4 Likes

I feel like this duck analogy is in order again...

3 Likes