Sub topic 5
Adding items with append, extend and insert
This chapter assumes you can run Python code, know how to index a list, and know that lists are mutable. Here you will learn the three methods that add items to an existing list, the differences that cause most bugs, and what each one costs.
The working model
append, extend and insert change the list in place. They don't build a new list, and each one returns None. Every name that refers to the list sees the change.
| Method | Adds | Where | Argument |
|---|---|---|---|
| `append(x)` | exactly one object | at the end | any object |
| `extend(it)` | each item of `it` | at the end | any iterable |
| `insert(i, x)` | exactly one object | before index `i` | an index and any object |
The most common mistake is treating these as expressions that return the new list:
tasks = ["write", "test"]
tasks = tasks.append("deploy") # wrong: rebinds tasks to None
print(tasks) # NoneCall the method as a statement and leave the name alone.
append: add one object
append puts its argument at the end of the list as a single element, whatever that argument is.
tasks = ["write", "test"]
tasks.append("deploy")
print(tasks) # ['write', 'test', 'deploy']
result = tasks.append("review")
print(result) # None
print(len(tasks)) # 4If the argument is itself a list, the list becomes one nested element. It is not unpacked.
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
print(len(a)) # 3Appending also stores a reference to the object, not a copy. If you keep changing the same object, every appended slot shows the latest state:
row = [0, 0]
rows = []
for i in range(2):
row[0] = i
rows.append(row)
print(rows) # [[1, 0], [1, 0]]Both entries are the same list. To store separate rows, create a new list on each pass, for example rows.append([i, 0]), or append row.copy().
extend: add many items
extend takes an iterable and appends each of its items in order. The iterable can be a list, tuple, string, dict, set, range, file, or generator.
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]
letters = ["a"]
letters.extend("bc") # a string yields characters
letters.extend(("d", "e")) # a tuple
letters.extend({"f": 1}) # a dict yields its keys
letters.extend(x for x in "gh") # a generator
print(letters) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']Two consequences are worth remembering:
- Passing a string adds one item per character. To add a whole string, use
append. - Passing a non-iterable raises
TypeError.[1].extend(5)fails with'int' object is not iterable. It does not add a 5.
A list can extend itself. Python takes a snapshot of the original length first, so there is no endless loop:
a = [1, 2]
a.extend(a)
print(a) # [1, 2, 1, 2]Choosing between append and extend
insert: add at a position
insert(i, x) places x so that it ends up at index i. The item that was there, and everything after it, shifts one place to the right.
items = ["b", "c"]
items.insert(0, "a") # ['a', 'b', 'c']
items.insert(2, "x") # ['a', 'b', 'x', 'c']
items.insert(-1, "y") # before the last item
print(items) # ['a', 'b', 'x', 'y', 'c']
items.insert(100, "z") # too large: goes to the end
items.insert(-100, "start") # too small: goes to the front
print(items) # ['start', 'a', 'b', 'x', 'y', 'c', 'z']Unlike indexing, insert never raises IndexError. An index past either end is clamped to the nearest end. That makes it forgiving, but a typo in the index will silently put an item in the wrong place.
Negative indices need care. insert(-1, x) puts x before the last item, not after it. To add after the last item, use append.
Related ways to add items
The + and += operators
Both operators join lists, but they behave differently with respect to aliases.
a = [1, 2]
b = a
a += [3] # same as a.extend([3]): modifies the shared list
print(b) # [1, 2, 3]
a = a + [4] # builds a new list and rebinds a
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]a += x calls the in-place behavior, so it accepts any iterable, just like extend. a + x requires another list on the right and creates a new one.
nums = [1]
nums += (2, 3) # works: [1, 2, 3]
# nums + (4,) # TypeError: can only concatenate list (not "tuple") to list
print(nums)Slice assignment
Assigning to an empty slice inserts a whole sequence at once. This is the way to insert many items at a position:
a = [1, 2, 3]
a[1:1] = ["x", "y"] # insert before index 1
print(a) # [1, 'x', 'y', 2, 3]
a[len(a):] = [7, 8] # same effect as a.extend([7, 8])
print(a) # [1, 'x', 'y', 2, 3, 7, 8]Common errors
Rebinding to None
As shown at the start, x = x.append(1) replaces your list with None. The same happens with return x.append(1) in a function. Python's own methods that change a list in place return None on purpose, so you can tell them apart from functions that return a new value.
Mutable default arguments
A default value is built once, when the function is defined. If it is a list and you append to it, the changes persist across calls:
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("a")) # ['a']
print(add_tag("b")) # ['a', 'b'] (surprise: same list as before)
def add_tag_fixed(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag_fixed("a")) # ['a']
print(add_tag_fixed("b")) # ['b']Growing a list while looping over it
A for loop walks the list by position. If the body keeps adding items, the loop keeps finding new ones:
nums = [1, 2, 3]
# for n in nums:
# nums.append(n) # never ends: each pass adds another item
for n in list(nums): # loop over a snapshot instead
nums.append(n * 10)
print(nums) # [1, 2, 3, 10, 20, 30]Looping over a copy, or collecting new items in a second list and extending afterward, keeps the logic predictable.
Nesting by accident
Using append where you meant extend gives a list inside a list. If a later step fails with something like unsupported operand type(s) for +: 'int' and 'list', check for an accidental nested list first.
What each method costs
Python lists are stored as a block of references. That layout explains the costs:
appendis amortized O(1). The list reserves spare room, so most appends just fill a free slot. Now and then it grows and copies, but averaged over many appends the cost per append stays constant.extendis O(k) for k new items.insert(i, x)is O(n − i), because every item after the position must move one slot. Inserting at index 0 is the worst case.
A loop that inserts at the front of a large list therefore does quadratic work overall. If you need to add at both ends, use collections.deque, whose appendleft is O(1):
from collections import deque
d = deque([2, 3])
d.appendleft(1)
d.append(4)
print(list(d)) # [1, 2, 3, 4]A common alternative is to append everything and call reverse() once at the end, or build the list in the order you need it.
Exercise
What do a and b contain after this code runs, and why?
a = [1, 2]
b = [1, 2]
a.append([3, 4])
b.extend([3, 4])
b.insert(1, "x")
Show answer
a is [1, 2, [3, 4]] because append adds the list as one nested item. b is [1, 'x', 2, 3, 4]: extend added 3 and 4 as separate items, giving [1, 2, 3, 4], and then insert(1, "x") placed "x" before index 1 and shifted the rest right.
Exercise
A function is meant to return a list with a new item added. It contains return items.append(new). What does it return, and how do you fix it?
Show answer
It returns None, because append changes the list in place and returns None. Call items.append(new) as its own statement and then return items. Alternatively, return a new list with return items + [new], which leaves the original unchanged.