Purify


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#


My code is working fine but I have a question regarding the creation of an empty list, I created the empty list before creating a function and it was showing some error but as soon as I created an empty list inside the function, the code worked.


I want to know the reason why creating an empty list outside the function does not work properly.


Replace this line with your code. 
def purify(x):
    even = []
    for i in x:
        if (i % 2 == 0):
            even.append(i)
    return even
print purify([1,2,4,4,6])


#2

The list needs to be created inside of the function so that it is scoped at the local level. This means that every time the function runs it will have access to a fresh clean list. If you create it outside of the function, depending on the rest of the code, it will be in the global or the field scope/class member (ruby may call the field scope/class member something else, forgive me, I'm a Java guy), meaning that the list is only defined when 1) the code runs for the first time (global scope) or 2) the class is instantiated (field scope/class member). Make sense?


#3

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