2

I know I can use "append()" to add an element to a list, but why does the assignment return None?

>>> a=[1,2,3]
>>> a.append(4)
>>> print a 
[1, 2, 3, 4]
>>> a=a.append(5)
>>> print a 
None
>>>
jkdev
  • 11,360
  • 15
  • 54
  • 77
Statham
  • 4,000
  • 2
  • 32
  • 45

3 Answers3

8

Because you're assigning an output to the act of appending which has no output, so instead of:

a=a.append(5)

you just want

a.append(5)
Keef Baker
  • 641
  • 4
  • 22
2

I try to explain in the easiest way: With:

a.append(5)

you are calling the function that adds something (in this case 5) to a

With:

a = a.append(5)

you are saying that a is equal the result of the funcion .append(). But append just modifies an existing list, it does not returns anything, and it does not, as you thought, return a new list with the element appended.

Matteo Secco
  • 613
  • 4
  • 10
  • 19
  • 1
    This is factually incorrect. If the append returned "the function of adding something to a list", then you would be able to call the result as a function. It is not doing that; it's simply returning nothing. – user108471 Mar 22 '17 at 15:16
  • Saying a = function() (where function() returns 1) is the same as a = 1. So if .append() returns *None*, a = append(5) will return *None* as well. However I tried to explain it better – Matteo Secco Mar 22 '17 at 15:24
  • That's true, but your statement "`a` is equal to the function of adding something to the list" is still misleading because `a` will not equal any kind of function. This is a distinction that is very important because variables _can_ equal functions in Python, and it is very common to have functions return functions (decorators, for example). – user108471 Mar 22 '17 at 15:29
  • Yeah, you're right, what I wanted to say is "*a* is equal to the result of the funcion of adding something to the list" – Matteo Secco Mar 22 '17 at 15:33
  • 1
    I think your latest edit helps a lot and makes it clear what you're trying to say. – user108471 Mar 22 '17 at 15:37
1

This just indicates that the "append" method does not return anything. It only modifies the existing list. It does not return an updated list.

Don't bother doing a = a.append(4). If you just want to add an entry to the list, do a.append(4) to modify a.

user108471
  • 2,488
  • 3
  • 28
  • 41