append()
appends the given object at the end of the list. The length is only incremented of +1.extend()
extends the list by appending the elements it contains one by one into the list. The length is incremented by the number of elements.
In more details
The append()
method is straight forward:
python> a = [1,2,3]
python> a.append(4)
python> a
[1, 2, 3, 4]
However, what happens if you need to add multiple elements at the same time? You could call the append()
method several times, but would it work to give the list of new elements to be added into the original list directly as a parameter? Let’s give a try:
python> a = [1,2,3]
python> a.append([4,5])
python> a
[1, 2, 3, [5, 6]] # vs. expected [1, 2, 3, 4, 5, 6]
The extend()
method intends to solve this problem:
python> b = [1,2,3]
python> b.append([4,5])
python> b
[1, 2, 3, 4, 5]
Note: the +
operator is equivalent to an extend
call.
python> a = [1,2,3]
python> a += [4,5]
python> a
[1, 2, 3, 4, 5]