-1

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?

Michael Bartz
  • 269
  • 1
  • 3
  • 10
  • Because you have to read the documentation. Who told you that `extend` would return something *different* than `None`? – Bakuriu Dec 30 '13 at 19:56
  • Because `extend` returns None. – BrenBarn Dec 30 '13 at 19:56
  • 3
    Questions like this make me wish there were a way to close with a link to the [reference docs](http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types), [tutorial](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists), or [FAQ](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) for things that are explained repeatedly by Python itself and don't need to be explained again on SO… – abarnert Dec 30 '13 at 20:03

2 Answers2

1

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']
  • Thanks. I pulled the trigger on the question too early. I did exactly what you suggested. – Michael Bartz Dec 31 '13 at 02:06
  • @MichaelBartz - Happy to have helped! Please don't forget to [accept one of the answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) though. Doing so helps keep SO organized. –  Dec 31 '13 at 02:16
1

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

abarnert
  • 354,177
  • 51
  • 601
  • 671