12. purify Python



I have already passed this exercise. However, I tried to find out another way … which didn’t work.
Like always I am confused.

Here’s the code:

def purify(x): #x is our list argument
  for i in x:  
    if i % 2 != 0:  # if a value in the list is not even... 
      del i   # ... then this value shall be deleted ...
  return x  #... and x shall return purified

That’s the error message:

Your function fails on purify([1]). It returns [1] when it should return [].

What’s wrong with the code?

Thanks in advance!


same problem again, i contains copy values from the list. Any change made to it won’t persist.

del deletes based on index, not on value (i contains values). But going for a del/remove approach is very difficult, because of index shift.

lists can’t have empty indexes, so lets say you have:

4   5    5   4
# indexes
0   1    2   3

you loop over the list, then remove the 5 from index 1. Then everything to the right of the removed item shifts one spot to the left:

4    5   4
# indexes
0    1   2

then the loop continues to the next index (2), causing the second 5 to be skipped


I see.

So just for a deeper understanding:
Let’s say del also deletes values. Wouldn’t it still work since the changes made on i would not persist?


it can delete values, using indexes.

you really need to delete from the list, so for example remove:


i don’t think you can delete an integer value by doing del i


Cool, now it works!
I just replaced del i with x.remove(i). So .remove() isn’t restricted on indices…


yes, now you are actually removing from the list (x), which we can achieve with del as well:

for i in range(len(x)):
   if i % 2 != 0:
       del x[i] 

we use range to get indices, but this still won’t work when you have lists with successive odd numbers.


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