Python A Checklist for Common Bugs
What you will learn
- A checklist of frequent Python bugs, each with a tiny example
- How to recognise the symptom and the usual cure
- Which earlier lessons explain each in depth
- A routine to review your own code
1. How to use this lesson
Most bugs are not new; they repeat. This lesson collects the most common ones with a short example, the surprising result (all outputs were produced with Python 3.13) and the fix. Skim it now; return to it when something behaves oddly. The numbers in brackets point to the lesson that explains the topic in full.
2. Counting and indexing
Off-by-one. range and slices stop before the end (lessons 6.2 and 4.2):
print(list(range(1, 5)), list(range(5))[-1], "abc"[1:3])
[1, 2, 3, 4] 4 bc
range(1, 5) does not include 5; "abc"[1:3] is characters 1 and 2. Cure: test the first, last and empty cases; write the expected result by hand first.
Slicing and indexes. The last item is t[-1] or t[len(t) - 1]; t[1:-1] drops both ends:
t = [10, 20, 30, 40]
print(t[:2] + t[2:], t[-1], t[len(t) - 1], t[1:-1])
[10, 20, 30, 40] 40 40 [20, 30]
3. Lists and other mutable data
Changing a list while looping over it skips items (lesson 7.5):
nums = [2, 4, 6, 8, 1]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
print([n for n in [2, 4, 6, 8, 1] if n % 2])
[4, 8, 1]
[1]
Removing an item shifts the rest left, so the loop steps over its neighbour. Cure: build a new list (a comprehension) or loop over a copy.
Repeated references. [[0] * 3] * 2 makes two names for the same inner list (lesson 7.5):
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
Mutable default argument (lesson 11.9):
def add(x, acc=[]):
acc.append(x)
return acc
print(add(1), add(2))
[1, 2] [1, 2]
(Both calls share one list; the single print shows its final state twice.) Cure: acc=None, then create the list inside.
Shallow copy. dict.copy() and list[:] copy only the outer layer (lesson 9.5):
import copy
orig = {"k": [1]}
sh = orig.copy()
sh["k"].append(2)
dp = copy.deepcopy(orig)
dp["k"].append(3)
print(orig, dp)
{'k': [1, 2]} {'k': [1, 2, 3]}
The shallow copy shared the inner list with orig; the deep copy did not.
Methods that return None. list.sort(), append, reverse change the list and return None (lesson 7.4):
x = [3, 1, 2]
y = x.sort()
print(y, x, sorted([3, 1, 2]))
None [1, 2, 3] [1, 2, 3]
Writing x = x.sort() throws the list away. Cure: x.sort() alone, or x = sorted(x).
Quick check: what does `[1, 2, 3].append(4)` return?
None. It changes the list in place.
4. Comparing and converting
is versus ==. == compares values; is asks whether two names are the very same object:
a = [1]
b = [1]
print(a == b, a is b, "x" == "x")
True False True
Use is only for None (x is None). Cure: default to ==.
Float equality (lesson 3.4):
print(0.1 + 0.2 == 0.3, round(0.1 + 0.2, 10) == 0.3)
False True
Cure: math.isclose, or round, or use integers (cents) or Decimal for money.
Text versus numbers, and the division operators:
print(7 / 2, 7 // 2, -7 // 2, "5" + "5", int("5") + int("5"), "5" * 3)
3.5 3 -4 55 10 555
input() and file data are text: "5" + "5" is "55". // rounds down (toward minus infinity), so -7 // 2 is -4. Cure: convert at the edge (int(...)) and check types when a result looks odd.
Truthiness. Empty things and zero are false; the text "0" is true (lesson 5.3):
print(bool(0), bool(""), bool([]), bool("0"), bool([0]), None == False, not None)
False False False True True False True
Operator precedence. and binds tighter than or; use parentheses when mixing:
print(1 or 2 and 0, (1 or 2) and 0, not 1 == 2)
1 0 True
Strings: string methods return new strings, because strings cannot change (lesson 4.7):
s = "hello"
s.upper()
print(s, " x ".strip())
hello x
The upper-case result was discarded; write s = s.upper(). Also remember that comparison by letter order puts capitals first: "a" < "B" is False, and sorted(["b", "A", "a"]) gives ['A', 'a', 'b'].
5. Names and scope
Shadowing a built-in. Naming a variable list, sum, max, str, id or input hides the real function (lesson 11.5):
list = [1, 2]
try:
list("abc")
except TypeError as e:
print("TypeError:", e)
del list # remove the shadowing name again
TypeError: 'list' object is not callable
Cure: choose other names (items, total); delete the stray name with del list if you did it in a console.
Local versus global (lesson 11.5):
count = 0
def bump():
count = 1 # creates a LOCAL name
bump()
print(count)
def bump2():
global count
count += 1
bump2()
print(count)
0
1
Assigning inside a function makes the name local. Better than global: pass values in and return results.
Late binding in closures (lesson 11.10): functions made in a loop all see the loop variable's final value:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
[2, 2, 2]
[0, 1, 2]
Cure: bind the current value as a default argument (i=i).
6. Iterators and structure
Exhausted iterators (lesson 12.4): a generator can be used once.
g = (i for i in range(3))
print(list(g), list(g))
[0, 1, 2] []
Missing dictionary keys: d["b"] raises KeyError; d.get("b") returns None, d.get("b", 0) a default (lesson 9.2).
Tuples need the comma:
print(type((1)), type((1,)), type(()))
<class 'int'> <class 'tuple'> <class 'tuple'>
Loop else runs when the loop was not ended by break (lesson 6.3), which surprises people who think it means "if the loop was empty".
7. A review routine
Before you say "it works", ask:
- Empty: what if the input is empty,
None, or has one item? - Boundaries: first and last item, equal values, zero, negative numbers.
- Types: is this really a number or still text? A list or a generator?
- Copies: do two names share one mutable object?
- Mutation: does a function change its argument when the caller does not expect it?
- Order and ties: does the code rely on an order that is not guaranteed?
- Floats and money: exact equality, rounding.
- Errors: which exceptions can happen here, and who handles them (lesson 14.1)?
- Resources: are files closed (
with)? - Names: does any variable shadow a built-in?
Then test the answers to these questions (lesson 18.4), and when a bug does appear, debug with a method (lesson 18.1).
Worked example: cleaning and summarising scores, with the checklist in mind
The function reads raw text values such as ['70', ' 85', 'x', '', '92 '], keeps the valid ones, and summarises. Each line below guards against a bug from the checklist.
def clean_scores(raw):
"""Turn ['70', ' 85', 'x', '', '92 '] into [70, 85, 92]."""
scores = []
for item in raw:
item = item.strip()
if not item:
continue
try:
scores.append(int(item))
except ValueError:
continue
return scores
def summarise(scores, pass_mark=50):
if not scores:
return {"count": 0, "average": None, "passed": 0}
average = sum(scores) / len(scores)
return {"count": len(scores), "average": round(average, 2),
"passed": sum(1 for s in scores if s >= pass_mark)}
print(summarise(clean_scores(["70", " 85", "x", "", "92 ", "45"])))
print(summarise(clean_scores([])))
print(summarise(clean_scores(["a", " "])))
{'count': 4, 'average': 73.0, 'passed': 3}
{'count': 0, 'average': None, 'passed': 0}
{'count': 0, 'average': None, 'passed': 0}
| Line of code | Bug it prevents |
|---|---|
item.strip() and the int conversion |
text versus numbers, stray spaces |
if not item: continue |
the empty string would crash int("") |
try ... except ValueError |
the bad value x |
a new scores = [] inside the function |
no shared mutable default |
if not scores guard in summarise |
division by zero on empty input |
>= pass_mark |
the boundary: exactly 50 passes |
round(average, 2) |
printing a long float |
The scores are made up. Notice that the last two calls (an empty list, and a list of only invalid items) give the same safe answer: the edge cases were thought about in advance.
Common mistakes
- Assuming the bug is somewhere exotic before checking the usual suspects.
- Fixing a symptom (adding a special case) instead of the cause.
- Never testing empty input.
- Trusting
inputand file data to be clean. - Not reading the actual error message.
- Changing several things at once while debugging.
- Repeating a bug already fixed, because no test was written for it.
Key takeaways
- Most bugs are familiar ones: off-by-one, modifying a list while looping, shared references, mutable defaults,
isversus==, float equality, text versus numbers,Nonefromsort, shadowed names, scope, late-binding closures, shallow copies, exhausted iterators. - Learn the symptom, then the cure: new list,
copy.deepcopy,Nonedefault,math.isclose, conversion at the edges, different names. - Review code with a routine: empty, boundaries, types, copies, mutation, order, floats, errors, resources, names.
- Write a test for every bug you fix.
Practice
1. What does this print, and why? x = [3, 1, 2]; y = x.sort(); print(y)
Show answer
None. sort() sorts the list in place and returns None.
2. How do you create a 3-by-3 grid of zeros whose rows are independent?
Show answer
[[0] * 3 for _ in range(3)].
3. Why are [lambda: i for i in range(3)] all returning 2?
Show answer
Each lambda looks up i when it is called, after the loop finished and i is 2. Binding lambda i=i: i captures the value at creation time.
4. Which comparison is safe for floats: a == b or math.isclose(a, b)?
Show answer
math.isclose(a, b), because float results often differ in the last digits.
5. After s = "hello"; s.upper(), what is s?
Show answer
Still "hello". Strings are immutable; upper() returned a new string that was discarded.
6. Name three edge cases to test for any function that processes a list.
Show answer
An empty list, a list with one item, and a list with duplicate or extreme values (also a list containing None or the wrong type, if relevant).