0

In codecademy, there was an exercise about defining a function to "purify" a list of number so that all odd numbers will be omitted from the list.

This instruction allowed me to first think of removing odd numbers from the list, hence I made the following function:

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

then tested on something like:
print(purify([1,1,2,3,4]))

To my surprise, this did not work as expected to printed the list [2,4], but rather printed [1,2,4].

My colleague then suggested that I approach it by appending numbers to a new list, which worked.

def purify(x):
    newx=[]
    for n in x:
        if n%2==0:
            newx.append(n)
    return newx

but they couldn't explain why the first method does not work.

Why can't the first method remove the second "1" on the list?

LHC2012
  • 187
  • 6
  • See [this](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating). Read Alex Martellis answer. It's a general convention in python to return None if mutating the input value. If you return something, return a new list. This is what your second function does. – Paul Rooney Jul 03 '19 at 02:18
  • Thank you, I read it and understand the concept now. – LHC2012 Jul 03 '19 at 02:26

0 Answers0