Purify : problem with a loop



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:
  return newapport


lets this our list:


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]
print x
print x.index(7)


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


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 ?



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


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:
count -=1
return newapport>


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


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