Sub topic 4
Identity, equality, and mutability
This chapter assumes you know that an assignment binds a name to an object, and that you can run Python code and use print(). It explains how to tell whether two names refer to the same object, and why changing an object sometimes affects more than one name.
Identity versus equality
Every object has an identity, which is a number that stays fixed for the object's lifetime. The built-in id() function returns it. Python offers two comparisons:
==tests equality: do the two objects have the same value?istests identity: are the two names bound to the very same object?
a = [1, 2]
b = a
c = [1, 2]
print(a == b, a is b)
print(a == c, a is c)
print(id(a) == id(b))This prints True True, then True False, then True. The lists a and c hold equal contents but are two separate objects. The names a and b point at one object.
Use == for comparing values. Reserve is for singletons, mainly None, as in if result is None:.
Mutable and immutable objects
A mutable object can change in place without changing its identity. An immutable object cannot. Any "change" to an immutable object produces a new object.
| Type | Mutable? |
|---|---|
| `int`, `float`, `bool` | No |
| `str`, `tuple` | No |
| `list`, `dict`, `set` | Yes |
This difference explains a common surprise:
x = 5
y = x
y += 1
print(x, y)
a = [1, 2]
b = a
b.append(3)
print(a)
print(a is b)The output is 5 6, then [1, 2, 3], then True. Integers are immutable, so y += 1 builds a new integer and rebinds y. The name x still points at 5. A list is mutable, so b.append(3) changes the one shared object. Both names see the change.
Common errors
- Using
isto compare values.x is 1000may appear to work in one run and fail in another, because whether two equal numbers or strings share an object is an implementation detail. Use==. - Expecting a copy from assignment. After
b = a, changingbthrough a method such asappendalso changesa. - Assuming a tuple is deeply frozen. A tuple's slots cannot be rebound, but a mutable object stored inside it can still change:
t = ([1], 2)
t[0].append(99)
print(t)This prints ([1, 99], 2). The tuple still holds the same list, and the list changed.
Checking your understanding
Exercise
After running p = [1, 2], q = p, q = q + [3], what do p and q contain, and is p is q true? (Hint: q + [3] builds a new list.)
Show answer
p is [1, 2] and q is [1, 2, 3], so p is q is False. The expression q + [3] creates a new list, and the assignment rebinds q to it. The original list, still bound to p, is not modified.
Exercise
Which comparison should you write to check whether a variable value holds None, and why?
Show answer
value is None. None is a singleton, so there is exactly one such object, and an identity check is the idiomatic and reliable test.