Purify : problem with a loop


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/purify?action=lesson_resume

Hi,
My code seems to be unable to remove 2 uneven numbers in a row, how come is that? probably something with the loop.

this is what it should do:
Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result.

def purify(apport):
  newapport = apport
  for i in newapport:
    if i % 2 != 0:
      newapport.remove(i)
  return newapport

#2

lets this our list:

[5,7]

we have two values: 5 at index 0, and 7 at index 1

if we remove the 5 from index 0, the list can’t have an empty index 0, so the 7 of index 1 moves to index 0:

x = [5,7]
x.remove(5)
print x
print x.index(7)

see?

After this, the loop just moves to the next index, causing a skip


#3

this is clear. thanks for your explaination.

do you have a solution if I want to improve this code? maybe using a pop or del ?

thanks


#4

del is very likely even more problematic given this might give an index error

personally, i wouldn’t use remove/del/pop at all

The opposite approach (append even numbers to new list) is much easier


#5

ok thanks for the advice.

I eventually passed the exercice with the following code (less pure), which use del but starts from the end:

def purify(apport):
newapport = apport
count = len(newapport)
print count
print newapport[count-1]
while count > 0:
if newapport[count-1] % 2 != 0:
del(newapport[count-1])
count -=1
return newapport>


#6

that is a possibility, looping in reverse doesn’t give index shift which allows for things like:

def purify(numbers):
  for index, value in reversed(list(enumerate(numbers))):
    if value % 2:
      del numbers[index]
  return numbers
  
print purify([4,5,5,4])

or range() can also be used

an easier solution might be to make a copy of the list, looping over one list and removing from another list (identical list) doesn’t give index shift as well


#7

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