12/15 I need clarification


#1

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

I wan’t to know why my code here doesn’t work, specifically line 8:
Faulty code

def purify(num_list):
   is_even = []
   for i in num_list:
     if i % 2 == 0:
       print "This is an even #"
       print i
       is_even = is_even.append(i)
   return is_even

Good code

def purify(num_list):
   is_even = []
   for i in num_list:
     if i % 2 == 0:
       print "This is an even #"
       print i
       is_even.append(i)
   return is_even

If I remove the equality is_even and simply leave it as is_even.append(i) it works.


#2

We cannot assign a statement except as a function expression return value.

is_even.append(i)

is a statement containing a function expression. The assignment would be None since the append method has no return value.


#3

noob question, why is does the “return” only append a single item, if it’s under the if statement, where as it returns all elements under the for.

Does the return only runs for the first iteration that it finds in a if statement? but if its under the for it runs for the entire list.


#4

The return line does not execute until the loop is complete. The list gets built in the loop, and will consist of only even numbers.


#5

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