Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why [].append(1) is None [duplicate]

Tags:

python

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?

like image 945
tdolydong Avatar asked Dec 11 '22 11:12

tdolydong


1 Answers

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.

like image 157
unwind Avatar answered Dec 24 '22 06:12

unwind