Deltos Deltos - 2 months ago 5
Python Question

Script which deletes odd numbers from a list (Python)

I've written a function designed to delete all odd numbers from a list.

def purify(l):
for e in range(len(l)):
if l[e] % 2 != 0:
del l[e]
return l

v = [4, 5, 5, 6]
print purify(v)


But when it starts executing list v it doesn't work from second cycle and gives an error: "IndexError: list index out of range". Why? What's wrong with the code?

Answer

The easiest way to do what you want may be by means of a list comprehension:

def purify(l):
    return [e for e in l if not (e % 2)]
Comments