>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
But:
>>> [1, 2, 3].append(4)
>>>
Why do list
methods in Python (such as insert
and append
) only work with defined variables?
>>> a = [1, 2, 3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
But:
>>> [1, 2, 3].append(4)
>>>
Why do list
methods in Python (such as insert
and append
) only work with defined variables?
In the second sample nothing is printed, because append
, that was called on a list (note that append was actually performed), returns None
.
Alternatively you should mention that a.append(4)
also gave you a blank line (as your first sample shows), and final output of a first code sample was a representation of result of a
expression, not a.append('4')
expression.
Nothing is printed after append
call in both cases because it is a representation of None
.
list.append
returns None
. a.append('4')
didn't print anything either since things which return None
don't print anything in the interactive interpreter ...
Note that your second method call did work. It appended '4'
to the list, you'll just never get to see it since you immediately lose any handle you had on the list you created.
It does work. It just doesn't print anything, the same way that a.append(4)
doesn't print anything. It's only because you saved the list as a variable that you can display its new value.
Another way to concatenate lists:
>>> [1, 2, 3] + [4]
[1, 2, 3, 4]
Note that in this case, a new list is created and returned. list.append
adds an item to an existing list and does not return anything.
It's not that the list methods works only with defined variables. It's that the specified method append of list always return None while change the internal state of the list in question.
The function only works with defined variables because that is how it is indented to work. From the python documentation:
list.append(x)
Add an item to the end of the list; equivalent to
a[len(a):] = [x]
.
Note that is does "work" in the sense that a value is returned and the function does not raise an exception. But the results are lost because you have no reference to the modified list.
!
- so in this case the function might be called append!
. Such a naming convention helps make the intent of the function more clear.