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?
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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With