Command Palette

Search for a command to run...

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

Names, objects, equality and identity

Add d = a[:] and print d is a and d == a. A slice is a new list.

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?

Names, objects, equality and identity
Sign in to run this example in your browser.

Expected output

a == c: True
a is c: False
a is b: True
a after b.append(4): [1, 2, 3, 4]
c unchanged: [1, 2, 3]
int -> type
str -> type
list -> type
builtin_function_or_method -> type
type -> type
True NoneType