Python: remove odd number from a list

What is wrong with the remove_odd() func?

You are iterating over a list while changing its size. This is causing it to skip one or more elements

Why don't you use list comprehension. Its more Pythonic, and readable

def remove_odd(l):
    return [e for e in l if e % 2 == 0]

remove_odd([4,5,4,7,9,11])
[4, 4]

Similarly you can write your remove_even routine

def remove_even(l):
    return [e for e in l if e % 2]

remove_even([4,5,4,7,9,11])
[5, 7, 9, 11]

Your function is working in another way than you would expect. The for loop takes first element, than second etc., so when you remove one element, others change their positions and can be skipped by it (and that happens in your case) when they are preceded by another odd number.

If you insist on using .remove() method, you must operate on a copy instead, like this:

def remove_odd(1):
    for i in l[:]:
        if i % 2 != 0:
            l.remove(i)
    return l

(l[:] is a shallow copy of list l)

However, I think using list comprehension would be much clearer:

def remove_odd(l):
    return [x for x in l if x % 2 == 0]

Tags:

Python