List manipulation in functions


#1




Oops, try again. list_extender([1, 2, 3, 4]) returned None, did you remember to return the result?


Why can't I assign the value of list.append(9) to list then return it?


n = [3, 5, 7]
# Add your function here
def list_extender(lst):
    lst = lst.append(9)
    return lst
print list_extender(n)


#2

Great question. The append function modifies a list, and then returns None.

You must simply call lst.append(9) then return the list.

The piece of internal code that performs this modification is:

listappend(PyListObject *self, PyObject *v)
{
    if (app1(self, v) == 0)
        Py_RETURN_NONE;
    return NULL;
}

So when you call lst = lst.append(9) you are actually saying lst = None.


#3

Oh,I didn't notice that it has no return value.Thank you so much,that helps me a lot.


#4

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