PURIFY. I solved this issue, but I'm unclear why i had to


#1



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


My first attempt...

returns "None" along with the following error message:
"Oops, try again. Your function crashed on [1] as input because your function throws a "'NoneType' object is not iterable" error."

my second attempt works just fine...

I'm not exactly clear on what the "[].append()" process is doing. My understanding is that this command will edit the current list and add whatever is in the (). I'm not sure why I cannot simply tell the program to return the appended list, and instead I have to append the list first and then return it. Can someone explain to me what python is actually doing when the .append() method is called?

see code below.

Thanks


1. 

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


2.

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


#2

For starters we would not want to return since it will exit the function withour completing the loop.

From a syntax perspective we cannot return a statement expression, in the normal sense. This is a valid return value, but it will be None, not the list you are expecting. append does not have a return, hence, None.

list.append(object)

This method appends the object to the list it is called upon.


#3

I think I gotcha. So in other words, using my first attempt, if I input the list [1, 2, 3], the loop would only iterate through the '1'?

As for your second point, I'm confused as to why "return list.append(i)" would not work, but in a previous exercise, I used "return ' '.join(list)" which returned the new list just fine.

Are these two operations doing something fundamentally different from each other? I'm not sure if I'm missing something or if I just need to learn more about what python will accept and what it won't.


#4

Because of the return statement in the loop, yes. It terminates the function prematurely.

If you can access an interactive console (say, labs repl.it), try this…

>>> n = [1,2,3]
>>> print (n.append(4))
None
>>> print (n)
[1, 2, 3, 4]
>>> 

That is because the str.join method returns a string, a real value, not None.

Functions that perform in place actions do not have a return.


#5

Gooootcha!! So str.join returns a string, not an edited list. That makes more sense. I got confused and thought it was returning a list.

And list.append() returns absolutely nothing.

Cool that helps a lot.

Thanks!


#6

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