Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a=list().append("hello") vs a=list(); a.append("hello") in python?

Tags:

python

list

I have

try:
    a = list().append('hello')

but a is NoneType

try:
    b = list()
    b.append('hello')

and b is a list type

I think list() returns a list object, and list().append('hello') will use the return list to do append, but why is the value of a None?

like image 222
Tanky Woo Avatar asked Sep 26 '26 15:09

Tanky Woo


2 Answers

list() does indeed return an empty list ([]), but the append method operates on a list in-place - it changes the list itself, and doesn't return a new list. It returns None instead.

For example:

>>> lst = []
>>> lst.append('hello')  # appends 'hello' to the list
>>> lst
['hello']
>>> result = lst.append('world')  # append method returns None
>>> result  # nothing is displayed
>>> print result
None
>>> lst  # the list contains 'world' as well now
['hello', 'world']
like image 155
Volatility Avatar answered Sep 28 '26 04:09

Volatility


a = list().append('hello')

The above line, would create a new list, then invoke the append() method, and just store the return code of append() to the variable a. And since the value is None, it just means that the append() method does not have a return value.

To confirm this, you could try this:

>>> a = list()
>>> result = a.append('hello')
>>> print a
['hello']
>>> print result
None
like image 35
Tuxdude Avatar answered Sep 28 '26 05:09

Tuxdude