Practice makes perfect 12.purify


#1

Hi im on this lesson right now and i wrote my code for it
i thought i had done it right but for some reason if there are 2 of the same odd number next to each other, it will remove the first one but not the second, and i dont get why it would do that

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

#2

Hi @h2zero,

Iterating through a list as items are being added or removed from it often interferes with the iteration, causing problems.

Instead of removing items from the original list, create a new empty list. Then within the loop, append even numbers to that new list, and return it after the loop has completed all of its iterations.


#3

thanks for the quick reply.
that makes a lot more sense now :slight_smile:


#4