Purify - only removing one odd number of two same values



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

i expected both odd numbers to be removed, any help would be appreciated

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


You need to create a copy of the original list being iterated in your loop.
numbers.return() messes up an internal counter that python does to iterate through your list using your index. By making a copy, Python can keep track of your original index as remove basically replaces the item on the next index to the one that has been removed.
Hence your 2nd 5 was skipped because it was in the previous 5's spot(index) which python thought it has removed.
Just simply add [:]after numbers in your for loop statement or do list in order to copy your numbers list:

Add[:] method

for num in numbers[:]:

Add list method

for num in list(numbers):


ah thanks alot willdo


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