Why does list.append() return None? [duplicate]

I am trying to calculate a postfix expression using Python, but it did not work. I think this is maybe a Python-related problem.

Any suggestions?

expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']

def add(a,b):
    return a + b
def multi(a,b):
    return a* b
def sub(a,b):
    return a - b
def div(a,b):
    return a/ b


def calc(opt,x,y):
    calculation  = {'+':lambda:add(x,y),
                     '*':lambda:multi(x,y),
                     '-':lambda:sub(x,y),
                     '/':lambda:div(x,y)}
    return calculation[opt]()



def eval_postfix(expression):
    a_list = []
    for one in expression:
        if type(one)==int:
            a_list.append(one)
        else:
            y=a_list.pop()
            x= a_list.pop()
            r = calc(one,x,y)
            a_list = a_list.append(r)
    return content

print eval_postfix(expression)

Solution 1:

Just replace a_list = a_list.append(r) with a_list.append(r).

Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear ...

Not directly related, but see Why doesn’t list.sort() return the sorted list?.

Solution 2:

The method append does not return anything:

>>> l=[]
>>> print l.append(2)
None

You must not write:

l = l.append(2)

But simply:

l.append(2)

In your example, replace:

a_list = a_list.append(r)

to

a_list.append(r)

Solution 3:

For return data on append use:

b = []   
a = b.__add__(['your_data_here'])

Solution 4:

append function mutates the list and it returns None. This is the piece of code which does that http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791

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

So, when you say

a_list = a_list.append(r)

you are actually assigning a_list with None. So, the next time when you refer to a_list, it is not pointing to the list but the None. So, as others have suggested, change

a_list = a_list.append(r)

to

a_list.append(r)

Solution 5:

just a thought, instead of those functions (which manipulates the actual data) returning None, they should have returned nothing. Then atleast the user would have caught the issue as it would have throwed an error stating some assignment error!! Comment your thoughts!!