Python List append(), extend() and insert()
There are three methods for adding values to a list. append adds one at the end, extend adds several at the end, and insert adds one at the position you choose. All three change the list itself and return no value.
list.append(value)
list.extend(values)
list.insert(index, value)
append: one at the end
The most common pattern is to start from an empty list and collect values one by one in a loop.
evens = []for x in [4, 7, 10, 3, 8]: if x % 2 == 0: evens.append(x)print(evens)print(len(evens))[4, 10, 8] 3
extend: adding several at the end
extend unpacks the list it is given and adds each value at the end. Give the same list to append and it is not unpacked: the whole list goes in as one item.
a = [1, 2]a.extend([3, 4])print(a, len(a)) b = [1, 2]b.append([3, 4])print(b, len(b)) a += [5]print(a)[1, 2, 3, 4] 4 [1, 2, [3, 4]] 3 [1, 2, 3, 4, 5]
a += [5] does the same thing as a.extend([5]).
insert: adding at the position you want
insert(i, value) puts the value before the item at index i. The values that were there from that position on each move back by one. To add at the very front, use insert(0, value).
q = ["b", "d"]q.insert(0, "a")print(q)q.insert(2, "c")print(q)q.insert(100, "z")q.insert(-1, "y")print(q)['a', 'b', 'd'] ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd', 'y', 'z']
Even when the position is larger than the length of the list, the value goes at the very end with no error. -1 means "before the last value", so it is not the very end.
Joining with + makes a new list
a + [value] does not change a. It makes a new list. The difference shows when another name also refers to the same list.
a = [1, 2]same = aa.append(3)print(a, same) a = a + [4]print(a, same)[1, 2, 3] [1, 2, 3] [1, 2, 3, 4] [1, 2, 3]
After append, same changed along with it, but after a = a + [4], only a refers to the new list.
Common mistakes
Storing the result of append back
a = [1]
a = a.append(2)
a.append(3)
→ AttributeError: 'NoneType' object has no attribute 'append'
append returns no value (None), so a stops being a list. Drop the a = and write just a.append(2).
Passing a single string to extend
names = ["kim"]
names.extend("lee")
print(names)
→ Each character goes in separately, instead of ['kim', 'lee']
extend unpacks what it gets before adding, and an unpacked string is characters. To add one value, use append("lee").
Giving append two values
a = []
a.append(1, 2)
→ TypeError: list.append() takes exactly one argument (2 given)
append takes only one value at a time. For several, use a.extend([1, 2]). To put a pair in one item, use a.append((1, 2)).
Assigning straight to an item of an empty list
a = []
a[0] = 5
→ IndexError: list assignment index out of range
a[i] = value can change only an item that already exists. To make new items, use append, or create the items first with a = [0] * n.