"Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]."

can't figure out why it's only taking out one of the 5s and not the second. any help would be great. thanks!

def purify(numbers):
    for x in numbers:
        if x%2!=0:
    return numbers


When we have for x in numbers python is going to go through each spot in numbers, so numbers[0], numbers[1], etc...
When we use .remove(x) it pulls out the number and everything slides in to fill the gab. What this means is that when you get to the first 5, which is numbers[1] and pull it, python then goes on to numbers[2], which used to also be a 5, but now is a 4 since there are now only three numbers in the list.

Basically the second 5 gets skipped over.


thanks for the response! that makes complete sense. i know i can switch my code to add the correct numbers to a new empyt list...but is there another function/way to just remove the numbers i want?


I would go with the route of creating a new list and appending the good numbers. You can do that in about 6 lines of code and it's pretty clean.

If, however, you still would like to just remove the numbers then you can use a while loop. It would look something like this:

def purify(numbers):
    x = len(numbers)
    while x > 0:
        if numbers[x-1]%2!=0:
        x -= 1    
    return numbers


thanks for the help :slight_smile:


or you could try this:

def purify(num):
   num1 = []
   for i in num:
      if i % 2 == 0:
    return num1


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.