Sub topic 13
Common mistakes and how to avoid them
This chapter collects the list bugs that show up most often in real code. Each one comes from behavior covered in earlier chapters. I assume you know indexing, slicing, the mutating methods (append, remove, pop, sort), list comprehensions, and the difference between a name and the object it refers to.
Most list bugs fall into two groups. In the first, two names share one list. In the second, a loop or method call changes a list while you are using it. The sections below follow that split.
Mistake 1: Treating assignment as copying
b = a does not copy the list. It makes b a second name for the same object.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # TrueTo get an independent list, copy it explicitly. Any of these make a shallow copy:
a = [1, 2, 3]
c1 = a.copy()
c2 = a[:]
c3 = list(a)
a.append(4)
print(c1, c2, c3) # [1, 2, 3] [1, 2, 3] [1, 2, 3]Aliasing also hides inside functions. A function that receives a list can change the caller's list. If the function should not do that, copy the list at the top of the function or return a new list.
def add_total(values):
values.append(sum(values)) # changes the caller's list
return values
data = [1, 2, 3]
add_total(data)
print(data) # [1, 2, 3, 6]Mistake 2: Shallow copies of nested lists
copy(), [:], and list() copy only the outer list. The inner lists are still shared between the original and the copy.
import copy
a = [[1, 2], [3]]
b = a.copy()
b[0].append(99)
print(a) # [[1, 2, 99], [3]]
c = copy.deepcopy(a)
c[0].append(100)
print(a) # [[1, 2, 99], [3]]
print(c) # [[1, 2, 99, 100], [3]]Use copy.deepcopy when the list contains other mutable objects and you need full independence. It is slower and copies everything it can reach, so use it only when you need it.
| Operation | New outer list? | New inner lists? |
|---|---|---|
| `b = a` | No | No |
| `a.copy()`, `a[:]`, `list(a)` | Yes | No |
| `copy.deepcopy(a)` | Yes | Yes |
Mistake 3: Building a grid with multiplication
Multiplying a list repeats references. With numbers this is harmless. With a list of lists, every row is the same object.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
print(bad[0] is bad[1]) # True
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]The comprehension runs [0] * 3 once per row, so each row is a new list. The inner [0] * 3 is safe because integers are immutable.
Mistake 4: Removing items while looping over the list
A for loop over a list walks an internal position counter. If you remove an item, everything after it shifts left, and the loop skips the item that moved into the current position.
nums = [2, 4, 6, 1]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 1] (4 was skipped, so it stayed)The expected result was [1]. Here are three safe fixes. The first is usually the best.
nums = [2, 4, 6, 1]
# 1. Build a new list with a comprehension
odds = [n for n in nums if n % 2 != 0]
print(odds) # [1]
# 2. Loop over a copy, change the original
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1]
# 3. Replace the contents in place, keeping the same list object
nums = [2, 4, 6, 1]
nums[:] = [n for n in nums if n % 2 != 0]
print(nums) # [1]Use the third form when other names or other objects hold a reference to the list and must see the change.
The same rule applies to adding items. Appending to a list while you iterate over it can make the loop run forever, because the loop keeps finding new items.
Mistake 5: Using the return value of a mutating method
Methods that change a list in place return None. This includes append, extend, insert, remove, sort, reverse, and clear. Only pop returns something useful, the removed item.
items = [3, 1, 2]
items = items.append(4)
print(items) # NoneAfter that line the list is gone, because the name now points to None. The same happens with items = items.sort(). Call the method as a statement, or use the function that returns a new list:
items = [3, 1, 2]
items.append(4)
ordered = sorted(items)
print(items) # [3, 1, 2, 4]
print(ordered) # [1, 2, 3, 4]A related slip is using append when you meant extend. append adds its argument as one item, so a list argument becomes a nested list.
x = [1, 2]
x.append([3, 4])
print(x) # [1, 2, [3, 4]]
y = [1, 2]
y.extend([3, 4])
print(y) # [1, 2, 3, 4]Mistake 6: A mutable default argument
Default values are evaluated once, when the function is defined. A list used as a default is therefore shared by every call that does not pass its own list.
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2]The standard fix is to use None as the default and create the list inside the function:
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [2]Mistake 7: Index errors and failed searches
Indexing past the end raises IndexError. Slicing never does. It clips to the available items.
letters = ["a", "b", "c"]
print(letters[1:10]) # ['b', 'c']
print(letters[10:]) # []
try:
print(letters[10])
except IndexError as err:
print(err) # list index out of rangeindex and remove raise ValueError when the item is not in the list. pop on an empty list raises IndexError. Guard these calls with in, or catch the exception:
letters = ["a", "b", "c"]
if "z" in letters:
letters.remove("z")
try:
pos = letters.index("z")
except ValueError:
pos = -1
print(pos) # -1Two details to remember:
remove(x)deletes only the first match. If the value appears several times, use a comprehension to drop them all.index(x)also returns only the first match.
Mistake 8: Slow patterns that look harmless
Some list operations work correctly but cost more than they appear to.
list.pop(0)andlist.insert(0, x)shift every other item, so each call takes time proportional to the list length. Using them in a loop over a large list gives quadratic total time. Usecollections.dequewithpopleftandappendleftfor queues.x in some_listscans the list from the start. Inside a loop over a big list, this also becomes quadratic. If you test membership often, build asetonce.result = result + [x]inside a loop copies the whole list each time. Useresult.append(x).
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
print(queue.popleft()) # 1
print(list(queue)) # [2, 3, 4]A quick diagnostic checklist
When a list holds values you did not expect, work through these questions in order:
- Is another name pointing at the same list? Check with
is, or printid()for both names. - Did you copy only the outer list when the items are themselves lists?
- Did you build rows with
*? - Are you changing the list inside a loop over that same list?
- Did you assign the result of
append,sort, or another in-place method? - Is a list used as a default argument?
Summary
- Assignment shares a list. Copy with
copy(),[:], orlist(), and usedeepcopyfor nested mutable items. - Build grids with a comprehension, not
*. - Never remove or add items while looping over the same list. Build a new list, or loop over a copy.
- In-place methods return
None. Do not assign their result. - Use
Noneas the default instead of[]. - Choose
dequefor queues andsetfor repeated membership tests.
Exercise
This function should return a new list of the positive numbers in values, and leave values unchanged. It has two bugs. Find them and write a corrected version.
def positives(values, result=[]):
for v in values:
if v <= 0:
values.remove(v)
else:
result.append(v)
return result
Show answer
Bug 1: result=[] is a mutable default, so results from earlier calls accumulate across calls. Bug 2: values.remove(v) changes the caller's list while the loop iterates over it, which skips items and breaks the "leave values unchanged" requirement. A corrected version builds a new list and never touches the input:
def positives(values):
return [v for v in values if v > 0]
For example, positives([-1, 0, 5, -2, 7]) returns [5, 7] on every call, and the argument list is unchanged.
Exercise
What do a and b contain after this code runs, and why?
a = [[1], [2]]
b = a.copy()
b[0].append(9)
b.append([3])
Show answer
a is [[1, 9], [2]] and b is [[1, 9], [2], [3]]. copy() made a new outer list, so b.append([3]) affects only b. The inner lists are shared, so b[0].append(9) changes the same inner list that a[0] refers to. Using copy.deepcopy(a) would leave a as [[1], [2]].