4

I use Python like this

>>>print [].append(1)
None

>>>ls = []
>>>ls.append(1)
>>>ls
[1]

why "[].append(1)" value is None ,and other one is real value?

tdolydong
  • 838
  • 6
  • 8

2 Answers2

13

Because the append() list method doesn't return the list, it just modifies the list it was called on. In this case, an anonymous list is modified and then thrown away.

The documentation isn't super-clear, but all it says is:

list.append(x)

Add an item to the end of the list; equivalent to a[len(a):] = [x].

For other methods, such as list.count(x), the word "return" occurs in the description, implying that if it doesn't, the method doesn't have a return value.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

append() does not return the list it modifies, but

Append the object item at the end of list list. Return 0 if successful; return -1 and set an exception if unsuccessful.

see http://docs.python.org/2/c-api/list.html

mnagel
  • 6,729
  • 4
  • 31
  • 66
  • 2
    You are linking to the internal C api documentation - the correct link is http://docs.python.org/2/tutorial/datastructures.html or http://docs.python.org/3.3/tutorial/datastructures.html for Python 3. – Wander Nauta Sep 04 '13 at 09:55
  • 2
    That return value is for the internal C API though, it doesn't seem the Python-level call is returning 0 since the OP is showing it returns `None`. – unwind Sep 04 '13 at 09:56
  • 1
    you are right, this is not ideal. the higher level python docs however are not explicit on what is returned, so you do not get a meaningful quote over there. – mnagel Sep 04 '13 at 09:58