What have I done wrong? 12/15


#1

Here is my code, it makes sense to me but it is wrong somehow? Any hints or help would be greatly appreciated. Thanks :smiley:

Here's my code:

newlist=[]
def purify(lists):
[tab] for number in lists:
[tab][tab]if number%2==0:
[tab][tab][tab] newlist.append(number)
[tab]return newlist


#2

You seemed to have encountered a bug with codecademy. I tried out your code, and if you put the newlist declaration inside your function, everything works out. However, I tried your code out in a python interpreter and your code works as is.

PS - When you're writing out your question the button that looks like </> allows you to enter code so you don't have to do [tab][tab][tab].


#3

Your declaration of the new list needs to be inside of the function, that it will be in the functions local scope, thus usable in every call of the function. Declaring a new list puts it outside of the function in a global scope, the function cannot write to it.

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

#4

Thank you so much for your help :blush:


#5

Thank you for the feedback and help :grinning:


#6

Old strong typing languages habits. C programs always needed declarations in the preprocessor. Hard to break old habits. I was making the same mistake.


#7

The actual issue is that newlist is not changed back to the empty list between codecademy's calls of purify().

# your code
purify([2])
print newlist   # => [2]
purify([1])
print newlist   # => still [2], not []

Bringing newlist = [] into the function resets it to the empty list every time. Good luck!