Purify function, index out of range


Hello everyone!

I'm stuck at the "purify" exercise, in which you have to clean a list from all its odd numbers.

I've got an "index out of range" error, whereas I think that I was cautious enough to avoid this error. Could you please tell me the problem?

def purify(liste):
    for i in range(len(liste)):
        if liste[i]%2==1:
            del new_list[i-a]
    return new_list


Hi @betajumper84099,

This statement actually results in list and new_list referring to the same list. ...


Therefore, if you make a change in one of them, you are making the same change in the other, because in reality they are the same object.

It is best not to alter the size of a sequence, such as a list, at the same time that you are iterating through it. Instead, start with a new empty list ...

    new_list = []

Then you can add the even numbers to that new list and return it when you are done.


If you still wanna keep the original values unaltered then you can use deepcopy.
In this if you make any changes to list1 will not affect list2.

from copy import deepcopy

list2 = deepcopy(list1)


Here's Python 3 documentation for copy and deepcopy that also applies to Python 2: 8.10. copy — Shallow and deep copy operations

It's good to be familiar with those two functions, because they are very useful for working with lists. However, for this particular exercise, you don't need to copy or deepcopy the original list. Just start with an empty list and build up the result by adding the even numbers to it.


Thank you so much for your prompt and accurate answers. They are really helpful and make me realize my mistake !