Sub topic 13
Common mistakes and how to avoid them
This chapter assumes you know how to create lists, index and slice them, call the common list methods, and write basic for loops. It collects the bugs that come up most often. Each one has a cause you can name and a fix you can apply.
Mistake 1: Using the return value of an in-place method
Methods such as sort, append, extend, insert, remove and reverse change the list and return None. Assigning their result throws your data away.
words = ["pear", "fig", "banana"]
words = words.sort()
print(words) # NoneCall the method on its own line and keep using the original name. If you want a new list, use sorted(words) instead.
Mistake 2: Aliasing instead of copying
Assignment copies the reference, not the list. Two names then point to the same object, so a change through one name shows up through the other.
a = [1, 2, 3]
b = a
c = a.copy()
a.append(4)
print(b) # [1, 2, 3, 4]
print(c) # [1, 2, 3]Use a.copy(), list(a) or a[:] when you need an independent list. These make a shallow copy. The outer list is new, but any inner lists are still shared. For nested data, use copy.deepcopy.
Mistake 3: Repeating a list of lists with `*`
Multiplying a list repeats references to the same inner list. It does not build new inner lists.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]A comprehension runs [0] * 3 once per row, so each row is a separate list.
Mistake 4: Removing items while looping
Deleting from a list during a for loop shifts the later items left. The loop's hidden position counter then skips an item.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3] (the second 2 was skipped)Build a new list instead of changing the one you are walking over.
nums = [1, 2, 2, 3, 4]
nums = [n for n in nums if n % 2 != 0]
print(nums) # [1, 3]If you must change the list in place, loop over a copy (for n in nums[:]) or loop backward by index.
Mistake 5: Index and lookup errors
Reading an index that does not exist raises IndexError. remove and index raise ValueError when the value is missing. pop on an empty list raises IndexError.
items = ["a", "b"]
if "z" in items:
items.remove("z")
if items:
print(items.pop())Test with in or check that the list is not empty before you call these methods. Slices never raise IndexError, so items[5:] returns [].
Mistake 6: Confusing `append` and `extend`
append adds one object. extend adds each item of an iterable.
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]Passing a string to extend adds each character, so [].extend("hi") gives ['h', 'i'].
Mistake 7: Mutable default arguments
A default value is created once, when the function is defined. A list default is therefore shared between calls.
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2]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 bucketQuick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Variable is `None` after a list call | Used the return value of an in-place method | Call the method alone, or use `sorted` |
| Changing one list changes another | Aliasing | `copy()`, or `deepcopy` for nested data |
| Rows in a grid change together | `[[0] * 3] * 2` | Use a comprehension |
| Loop skips items | List changed during iteration | Build a new list |
| `ValueError` or `IndexError` | Missing value or empty list | Check with `in` or truthiness first |
| List grows across calls | Mutable default argument | Default to `None` |
Exercise
What does this code print, and why? x = [3, 1, 2] then y = x.sort() then print(x, y)
Show answer
It prints [1, 2, 3] None. The sort method reorders x in place and returns None, so y is None. Use y = sorted(x) if you want a separate sorted list.
Exercise
A function def log(msg, history=[]) appends msg to history and returns it. Why does history keep growing across separate calls, and how do you fix it?
Show answer
The default list is created once when the function is defined, so every call that omits history shares it. Change the default to None and create a new list inside the function with if history is None: history = [].