def purify(numbers):
  for num in numbers:
    if num % 2 != 0:
  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]


You’re reading from numbers

for num in numbers:

while also modifying it


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


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


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)


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


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