Purify

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/purify?action=resume_content_item

Not sure why code not working. It only counts one number out a list

def purify(num):
  even = [ ]
  for l in num:
    if (l % 2) == 0:
      even.append(l)
    else:
      return even
1 Like

Let us assume that this is our function call:

purify([1, 2, 3])

The result we expect is [2]. Let us examine step by step what your function is doing.


  1. even = [] => we create empty list that will store our result
  2. for l in num => we iterate through our list
  3. l = 1 => because first element of num is 1
  4. if (1 % 2) == 0 => 1 is odd, so this evaluates to False, so we move to the else block (if it exists)
  5. return even => your function returns [] and terminates execution

Do you see what is wrong? The return statement was reached too soon, it should be placed after the whole for loop.

1 Like

Also I think the else statement is not needed. The function will continue to loop through the the elements and append them to the even list if i%2 = 0. Just make sure your ‘return even’ is indented at the same spacing as the for loop, otherwise it will be contained in the for loop and terminate after the first time an even number is evaluated.

1 Like