Search code examples
pythonlistappendnonetype

Why does append() always return None in Python?


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.


Solution

  • 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]
    >>> l + [4]
    [1,2,3,4]
    >>> 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"]