Read Code Fast

Lesson 12 Data flow

5 min read · Python · Quiz

follow one value, mutation versus copy, aliasing

What you'll learn

  • Tell a new value from a second name for the same one
  • Spot shallow copies and in-place changes that surprise the caller
  • Judge whether an AI change from copy to mutation is safe

The sneakiest bugs aren't in a calculation. They're in a value that changed somewhere else, because two names pointed at the same thing.

The idea

To follow data, pick one value and ask at every line: is this a new value, or the same one under another name? Lists and dicts are shared, not copied. b = a gives you a second name for the same object, and changing one changes both.

dict(order) or order.copy() makes a shallow copy: a new outer dict, but the same inner lists and dicts. copy.deepcopy copies everything. Some methods change their input in place, like sort and append. Others return something new. Know which is which.

discount.py
1def apply_discount(order, pct):2    updated = dict(order)3    updated["total"] = order["total"] * (1 - pct / 100)4    updated["items"].append({"sku": "GIFT", "qty": 1, "price": 0})5    return updated
  1. Line 2 A copy, so far so good. But dict(order) is shallow: updated["items"] is the very same list as order["items"].
  2. Line 3 Safe: assigning total changes only the new dict. The original keeps its old total.
  3. Line 4 The bug: append changes the shared list, so the caller's original order gets the gift item too.

Take away

  • Ask of every value: new, or the same one under another name?
  • dict(x), x.copy() and list(x) are shallow: inner objects are still shared.
  • Know which methods change their input in place, like sort and append.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.