Purify function, index out of range


#1

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):
    new_list=liste
    a=0
    for i in range(len(liste)):
        if liste[i]%2==1:
            del new_list[i-a]
            a+=1
    return new_list


#2

Hi @betajumper84099,

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

    new_list=liste

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.


#3

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.
Example.

from copy import deepcopy

list2 = deepcopy(list1)


#4

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.


#5

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


#6