user8079 user8079 - 2 months ago 4
Python Question

What is the difference between these two python methods?

I am a python newbie.

I have one python method which returns the list recursively (previous is the dictionary of string and s is just a string that is included in the previous dictionary)

def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict."
return [] if (s is None) else path(previous, previous[s]) + [s]


and this one which I believe should return the same result

def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict."
if s is None:
return []
else:
path(previous, previous[s]) + [s]


I was expecting that functionality wise those two methods are exactly identical, it's just that the first one is more consice. However, when I run the second methods,

I am receiving following error:


"TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'"


What am I doing wrong here?

Answer

You're missing a return statement in the else branch of the second method:

def path(previous, s):
    "Return a list of states that lead to state s, according to the previous dict."
    if s is None:
        return []
    else:
        return path(previous, previous[s]) + [s]

The first approach uses a ternary operator whose returned value (one of two) is returned by the return statement, therefore, the second needs a return statement in both branches.

Comments