Purify: managed to solve but need an explanation for code i wrote


#1


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

Oops, try again. Your function fails on purify([1]). It returns [2, 4, 6, 8] when it should return [].


Hey guys, I managed to fix my code but I don't understand about the positioning when it comes to defining a new list(in my case i used blist).

In the wrong code, I defined blist=[] above the purify function and I append to blist in the for loop.
However in the correct code, blist=[] was defined after defining purify function. I don't understand whats the difference, could someone help me on this? Thank you!

Wrong Code:
blist=[]
def purify(alist):
    for i in alist:
        if i % 2 == 0:
            blist.append(i)
    return blist        

Working Code:
def purify(alist):
    blist=[]
    for i in alist:
        if i % 2 == 0:
            blist.append(i)
    return blist


#2

i think its best if we let the code do the talking:

blist=[]
def purify(alist):
    for i in alist:
        if i % 2 == 0:
            blist.append(i)
    return blist  

print purify([2, 4, 6, 8])
print purify([1])

as you can see from this code, blist accumulates data, so the second function call blist will still contain data from the first function call, this shouldn't be

i guess it goes without saying what difference declaring blist inside of purify makes?


#3

When you have a function, variables and lists need to be called in the function, not before it like you have in your 'wrong code'.

Instructions:
Do not directly modify the list you are given as input; instead, return a new list with only the even numbers.

In your wrong code you overwrote the list you were given instead of returning a new list (blist). Since you defined blist in your working code in the function and then appended it, it worked. :slight_smile:


#4

so if i placed blist=[] within the function it doesnt store data from previous loops , ie if i tried 2 different lists the 2nd list would not have data from the 1st list. Is this intuition right?


#5

because then the second function call, blist=[] becomes an empty list again (the code in the function executes again, this include creating a new empty list)

furthermore, the great thing about functions is that we can put them in a separate file and then import them (good practice for big code base), if we attempt to import your function while blist=[] is outside the function, we would get an blist referenced before assignment error or something similar.


#6

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