Sub topic 5
Adding items with append, extend and insert
Lists are mutable, so you can grow them in place. This chapter covers the three methods that add items: append, extend and insert. It assumes you can run Python code, use the basic types int, str and bool, write for loops and if statements, and call methods.
What these methods have in common
All three methods change the existing list and return None. They do not build a new list. A common error is writing nums = nums.append(4), which replaces your list with None.
nums = [1, 2, 3]
result = nums.append(4)
print(nums) # [1, 2, 3, 4]
print(result) # Noneappend: add one item at the end
append(x) adds exactly one object to the end of the list. The object can be of any type, including another list.
nums = [1, 2, 3]
nums.append(4)
nums.append([5, 6])
print(nums) # [1, 2, 3, 4, [5, 6]]The last line shows the key point: append([5, 6]) adds the list as a single item, so nums now holds a nested list. If you wanted the items 5 and 6 added separately, use extend.
extend: add every item from an iterable
extend(iterable) takes any iterable (a list, tuple, string, range or generator) and adds each of its items to the end, one by one.
nums = [1, 2, 3]
nums.extend([4, 5])
nums.extend(range(6, 8))
nums.extend("ab")
print(nums) # [1, 2, 3, 4, 5, 6, 7, 'a', 'b']A string is an iterable of characters, so extend("ab") adds 'a' and 'b' separately. If you pass a non-iterable such as an int, you get a TypeError.
The += operator on a list behaves like extend. It also changes the list in place.
nums = [1, 2]
nums += [3, 4]
print(nums) # [1, 2, 3, 4]By contrast, nums + [3, 4] builds a new list and leaves nums unchanged.
insert: add an item at a position
insert(index, x) puts x before the item currently at index. Later items shift one position to the right.
letters = ["a", "c", "d"]
letters.insert(1, "b")
print(letters) # ['a', 'b', 'c', 'd']
letters.insert(0, "start")
letters.insert(100, "end")
print(letters) # ['start', 'a', 'b', 'c', 'd', 'end']insert does not raise IndexError for an index that is too large. An index past the end acts like append. A negative index counts from the end, so insert(-1, x) places x before the last item, not after it.
Choosing between them
| Goal | Method | Example result for `[1, 2]` |
|---|---|---|
| Add one object at the end | `append(3)` | `[1, 2, 3]` |
| Add one list as a single item | `append([3, 4])` | `[1, 2, [3, 4]]` |
| Add many items at the end | `extend([3, 4])` | `[1, 2, 3, 4]` |
| Add one item at a chosen position | `insert(0, 0)` | `[0, 1, 2]` |
How the methods differ
Exercises
Exercise
What are the values of items and r after running items = [1, 2] and then r = items.extend([3, [4, 5]])?
Show answer
items is [1, 2, 3, [4, 5]] and r is None. extend adds each item of the argument, so 3 and the inner list [4, 5] are added as two items. The inner list is not flattened. extend returns None.
Exercise
Starting from data = ["x", "y", "z"], write one call that makes data equal to ["x", "y", "w", "z"], and explain which index you chose.
Show answer
data.insert(2, "w"). insert places the new item before the item currently at index 2, which is "z", so "w" lands between "y" and "z". data.insert(-1, "w") also works here.