12. purify Python


#1

Hi,

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!
CR


#2

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:

#values
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:

#values
4    5   4
# indexes
0    1   2

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


#3

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?


#4

it can delete values, using indexes.

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

x.remove(i)

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


#5

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


#6

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.


#7

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