12/15 Purify Close but not Quite – Help!


#1

I have tried the following three variations. Each one only returns a list containing the first even number in the original list. For example, purify([4, 5, 5, 4]) returns [4] instead of [4, 4]. I suspect there is some issue with the numbers “moving” in the original list as it loops, which messes up the indexes for loop. But I don’t understand what’s causing this or how to prevent it. A fast answer would be appreciated! I’m not letting myself eat until I complete this exercise :wink:

Variation 1:

def purify(makeeven):
  for number in makeeven:
    even = []
    if number % 2 != 0:
      makeeven.remove(number)
    else:
      even.append(number)
  return even

Variation 2:

def purify(makeeven):
  for number in makeeven:
    even = []
    if number % 2 == 0:
      even.append(number)
  return even

Variation 3:

def purify(makeeven):
  for number in makeeven:
    even = []
    even.append(number)
    if number % 2 != 0:
      even.remove(number)
  return even

#2

This declaration should be before the loop.


#3

Awesome, thanks! Can you explain why that makes it work?


#4

Because if the list is declared inside the loop it gets cleared on every iteration. It needs to be initialized before the loop so it can grow with iterations.


#5

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