Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)
like image 266
newlife Avatar asked Nov 16 '13 09:11

newlife


2 Answers

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)
like image 73
Maxime Chéramy Avatar answered Oct 12 '22 13:10

Maxime Chéramy


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?.

like image 39
falsetru Avatar answered Oct 12 '22 12:10

falsetru