Why does append() always return None in Python?

starcodex picture starcodex · May 20, 2013 · Viewed 65.5k times · Source
list = [1, 2, 3]
print(list.append(4))   ## WRONG, print does not work, append() returns None

## RIGHT:
list.append(4)
print(list)  ## [1, 2, 3, 4]

I'm learning Python and I'm not sure if this problem is specific to the language and how append is implemented in Python.

Answer

xuanji picture xuanji · May 20, 2013

append is a mutating (destructive) operation (it modifies the list in place instead of of returning a new list). The idiomatic way to do the non-destructive equivalent of append would be

l = [1,2,3]
print l + [4] # [1,2,3,4]
print l # [1,2,3]

to answer your question, my guess is that if append returned the newly modified list, users might think that it was non-destructive, ie they might write code like

m = l.append("a")
n = l.append("b")

and expect n to be [1,2,3,"b"]