Purify


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#


The error message I get says "Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]."


I'm not sure why the for loop isn't cycling through to remove each odd number.


def purify(numbers):
    for num in numbers:
        if num % 2 != 0:
            numbers.remove(num)
    return numbers


Purify
#2

for the following list:

[4,5,5,4]

agree we have the following indexes: 0, 1, 2 and 3

so, the loop uses this indexes to loop through the list. First up, index 0. If condition is checked, is false, the loop moves to the next index. If condition is true, so 5 is removed

however, lists can't have empty indexes, so everything to the right of the removed number shifts to the left (this is called index shift), so we get:

4    5    4
0    1    2

the top row is the values in the list, the bottom row the indexes. Okay, that sorted, the loop can start its next iteration, so it moves on to index 2, causing the 5 at index 1 to be skipped (because of the index shift that occurred)


#3

Thanks for the quick response. Should I then not be using the remove method to solve the challenge?


#4

i can't say you shouldn't, that is up to you. I would advise against it, yes. The index shift you have to deal with makes it a pretty tricky way to solve the problem

let me know if you need more help, like a hint in which direction you need to search, or if you get stuck again, post an updated version of your code


#5

Would love a hint as to which direction I should be looking in terms of methods to utilize for this particular challenge.


#6

maybe we can use the opposite approach? Not removing, but adding by using .append()


#7

Thanks! I was able to figure it out with append!


#8

good to hear :slight_smile: much better approach then removing :wink:


#9