Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.1 — Objects, Identity and References
Python · Example 2 of 3

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.

01

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.

02

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.

03

Show with three pairs (two int("1000"), two int("7"), two [1] lists) that equal does not mean same object.

04

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

01

What is the difference between == and is, and when is each correct?

02

Is Python pass-by-value or pass-by-reference? Explain with a function that mutates and one that rebinds.

03

Why is def f(x, items=[]) dangerous, and how do you fix it?

04

Why can a is b be True for two small integers but False for two large ones? Should your code rely on this?

05

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?

Caches, argument passing and the default-argument trap
Sign in to run this example in your browser.

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'],)