Why does this python return statement NOT work?
def f():
return ['The world needs more engineers', 'I need a raise', ]
def g():
x = []
return x.extend(f())
a = g()
print a
The return value for "a" is None. Why?
Why does this python return statement NOT work?
def f():
return ['The world needs more engineers', 'I need a raise', ]
def g():
x = []
return x.extend(f())
a = g()
print a
The return value for "a" is None. Why?
You are getting None
because this line in function g
:
return x.extend(f())
returns the result of using list.extend
on x
.
list.extend
operates in-place. Meaning, it always returns None
and thus should be on its own line.
To fix the problem, make your code like this:
def f():
return ['The world needs more engineers', 'I need a raise', ]
def g():
x = []
x.extend(f()) # Use list.extend on its own line
return x
a = g()
print a
Output:
['The world needs more engineers', 'I need a raise']
The return value for "a" is None. Why?
Because that's what the list.extend
method returns.
Almost all methods in Python that mutate a value in-place return None
. So, you want either this:
x.extend(f())
return x
(mutate the value, then return it)
… or this:
return x + f()
(create and return a new value)
If you're wondering why Python was designed this way, it's explained in the FAQ. It talks about list.sort
, but the same logic is true for other cases. (Note that, just as sort
has a companion new-list-creating function sorted
, extend
has a companion new-list-creating operator +
. This isn't always true, but even when it isn't, the mutating method will return None
.)