Purify


#1
def purify(numbers):
  for num in numbers:
    if num % 2 != 0:
      numbers.remove(num)
  return numbers

print purify([4,5,5,4])

I’m not sure why this prints out [4, 5, 4] instead of [4, 4]. I tried using enumerate and deleting the index, but it also returned [4, 5, 4]


#2

You’re reading from numbers

for num in numbers:

while also modifying it

numbers.remove(num)

Is it possible that one of those is having an effect on how the other behaves?


#3

Oh, I see. remove(num) is modifying the array and its indices, which is why it’s ignoring the second 5.


#4

The remove method causes elements to move, but the iterator keeps increasing its position each time.

You can compensate for the removal, but a cleaner solution is to read and modify two separate objects.

Ideally you’d also avoid using the remove method since that loops through the whole list on each use (really inefficient, not noticeable for small lists, but gets really bad as the size of the list grows)


#5

You’re better making a new list,
then using the modulus % 2 == 0 to check for even numbers
then if true, use append to add the value to your new list
last return results


#6

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