-1

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?

Alex F
  • 57
  • 5
  • Also see the explanation and other linked questions at [Removing items from a list while iterating over the list](http://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list). – PM 2Ring Sep 24 '16 at 10:35
  • Deleting / removing elements of a list that you're iterating over is tricky. It _is_ possible, but it's a bit like sawing off a tree branch that you're sitting on. If you don't do it right Bad Things™ happen. :) But anyway, it's faster to just build a new list containing the elements you want to keep. Removing list elements can be time-consuming: when you remove an element all subsequent elements have to be moved down, so it's best not to remove a list element unless it's near the end of the list. – PM 2Ring Sep 24 '16 at 10:41
  • Thank you! I got it – Alex F Sep 24 '16 at 10:45

2 Answers2

1

You may use list comprehension as :

lst = [4, 5, 5, 6]

lst_even = [i for i in lst if not i%2]

print v_purified
ZdaR
  • 22,343
  • 7
  • 66
  • 87
0

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)]
Schmuddi
  • 1,995
  • 21
  • 35