Caches, argument passing and the default-argument trap
The cache results are CPython details. Do not rely on them in real code.
Every value in Python is an object with an identity, a type and a value, and a variable is just a name pointing at an object. Knowing the difference between == (same value) and is (same object) explains aliasing, argument passing and the mutable default argument trap.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Predict the output: a = [1, 2], b = a, b += [3], c = a, c = c + [4]. Print a, b, c, and whether a is b and a is c.
Fix append_to(item, bucket=[]) so each call without a bucket starts with a new empty list. Show that two calls print ['a'] and ['b'], and that a list you pass in is used.
Show with three pairs (two int("1000"), two int("7"), two [1] lists) that equal does not mean same object.
Run t[0] += [3] on t = ([1], 2) inside try/except TypeError. Print the error type name and then t. Explain in a comment why the tuple still changed.
Explain it without notes
What is the difference between == and is, and when is each correct?
Is Python pass-by-value or pass-by-reference? Explain with a function that mutates and one that rebinds.
Why is def f(x, items=[]) dangerous, and how do you fix it?
Why can a is b be True for two small integers but False for two large ones? Should your code rely on this?
What does a += b do for a list, and what does it do for an int or a tuple? Why does t = ([1], 2); t[0] += [3] both fail and succeed?
Expected output
small ints share one object: True
big ints share one object: False
but they are equal: True
built strings same object: False
after sys.intern: True
after rebind: [1, 2]
after mutate: [1, 2, 99]
['a']
['a', 'b']
defaults live on the function: (['a', 'b'],)