list.append()
is an in-place operation, meaning that it modifies the state of the list
, instead of returning a new list
object.
All functions in Python return None
unless they explicitly return something else. The method a.append()
modifies a
itself, which means that there's nothing to return.
Another way you can see this behavior is in the difference between sorted(some_list)
and some_list.sort()
.
If you don't want to append "x"
to a
, then you'll need to use the second snippet, or you can simply concatenate:
>>> a = [1, 2, 3, 4]
>>> b = a[1:] + ["x"]
>>> b
[2, 3, 4, 'x']
To further clarify:
>>> a = [1, 2, 3, 4]
>>> b = a[1:].append("x")
>>> a
[1, 2, 3, 4]
>>> a[1:]
[2, 3, 4]
>>> type(b)
<class 'NoneType'>
Notice that b
is None
, since the list.append()
method returns None
. Notice also that a
wasn't actually modified. This is because you were appending to a slice of a
, but not actually saving that slice anywhere. Notice what happens if you do a.append("x")
:
>>> b = a.append("x")
>>> a
[1, 2, 3, 4, 'x']
>>> type(b)
<class 'NoneType'>
b
is still None
, but now a
got modified.
append
will returnNone
if it worked. There is not much more to it than that. – Agonizingappend
is avoid
function. This makes sense, thanks. – VernellvernenNone
. There are a few exceptions where following this rule would make the code harder to use (list.pop
is one example). But those are definitely exceptions and not the rule. – Bibliogonyappend
is an in place operation – Seriema