Sub topic 4
Identity, equality, and mutability
This chapter assumes you can run Python code and use print(). It also assumes you know that an assignment such as x = 5 binds a name to an object, and that type() reports the type of the object a name currently refers to. Here you learn how to ask whether two names refer to the same object, whether two objects hold the same value, and whether an object can change after you create it. These three questions explain most surprising Python behavior with names.
Three questions about any object
Every Python object has three properties.
- Identity is which object it is. It never changes during the object's lifetime.
id(obj)returns it as an integer, anda is btests whether two names refer to the same object. - Type is what kind of object it is.
type(obj)reports it. - Value is the data it holds.
a == btests whether two objects have equal values.
Identity and equality answer different questions. is asks "are these the same object?". == asks "do these objects count as equal?".
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)
print(a is b)
print(a is c)
print(id(a) == id(c))This prints True, False, True, True. The names a and b refer to two separate lists with equal contents. The name c is a second name for the same list that a refers to.
How equality works
The == operator asks the object to compare itself with another. Each type decides what "equal" means.
- Numbers of different types compare by numeric value:
1 == 1.0isTrue, even though1 is 1.0isFalse. boolis a subclass ofint, soTrue == 1isTrue.- Lists and tuples are equal when they have the same length and their items are pairwise equal.
- A float NaN (not a number) is never equal to anything, including itself.
nan = float("nan")
print(1 == 1.0)
print(True == 1)
print(nan == nan)
print(nan is nan)This prints True, True, False, True. The last line shows that identity and equality can disagree. Container comparisons check identity first as a shortcut, so [nan] == [nan] is True when both lists hold the same NaN object.
When to use `is`
Use == to compare values. Use is only to compare against singletons, which are objects of which exactly one exists. The common ones are None, True, and False. The usual case is None:
value = None
print(value is None)
print(value is not None)Do not use is to compare numbers or strings. Whether two equal numbers or strings are the same object is an implementation detail. CPython, the standard interpreter, reuses small integers and some strings, so is may appear to work in one test and fail in another. Recent Python versions emit a SyntaxWarning for code like x is 256.
Mutability
An object is mutable if its value can change in place, which means identity stays the same while the contents change. An object is immutable if its value can never change after creation. To get a different value you must create a different object.
| Type | Mutable? | Notes |
|---|---|---|
| `int`, `float`, `bool` | No | Arithmetic creates new objects |
| `str`, `bytes` | No | Methods return new objects |
| `tuple` | No | But its items may be mutable |
| `None` | No | A singleton |
| `list`, `dict`, `set` | Yes | Changed in place by methods and item assignment |
| `bytearray` | Yes | A mutable counterpart of `bytes` |
Immutability is a property of the object, not of the name. You can always rebind a name to a different object. You cannot change an immutable object itself.
Rebinding versus mutating
This is the most important distinction in the chapter. Rebinding changes which object a name refers to. Mutating changes the object itself, so every name that refers to it sees the change.
x = 5
y = x
y += 1
print(x, y)
a = [1, 2]
b = a
b.append(3)
print(a)
print(a is b)This prints 5 6, then [1, 2, 3], then True.
For integers, y += 1 computes a new int and rebinds y. The name x still refers to the original 5. For the list, b.append(3) modifies the one list object that both a and b refer to. Nothing was rebound.
Augmented assignment can do either
The statement a += value calls an in-place operation if the type provides one, and otherwise falls back to a = a + value. Lists provide an in-place version. Integers, strings, and tuples cannot, because they are immutable.
a = [1, 2]
b = a
a += [3]
print(b)
a = a + [4]
print(a, b)This prints [1, 2, 3], then [1, 2, 3, 4] [1, 2, 3]. The first operation changed the shared list, so b saw the new item. The second built a new list and rebound a, so b stayed as it was. The two forms look equivalent but behave differently when other names share the object.
Immutable containers with mutable contents
A tuple is immutable, but that only means it always holds the same item objects. If one of those items is mutable, the item can still change.
t = (1, [2])
t[1].append(3)
print(t)
try:
t[0] = 9
except TypeError as e:
print("TypeError:", e)The tuple prints as (1, [2, 3]). The assignment t[0] = 9 raises TypeError because a tuple does not support item assignment. Appending to the inner list works because it mutates the list, not the tuple.
This is also why mutable objects such as lists cannot be dictionary keys. A key must keep the same hash, and a mutable value could change its hash.
Copying objects
Assignment never copies. To get an independent object you must copy explicitly. A shallow copy creates a new outer container but reuses the same inner objects. A deep copy copies the inner objects too.
import copy
original = [[1, 2], [3]]
shallow = original.copy()
shallow[0].append(99)
print(original)
deep = copy.deepcopy(original)
deep[0].append(100)
print(original)
print(deep)This prints [[1, 2, 99], [3]] twice for original, then [[1, 2, 99, 100], [3]] for deep. The shallow copy is a new list, but its first item is the same inner list as in original, so the append shows through both. The deep copy has its own inner lists.
Other ways to make a shallow copy of a list are list(original) and original[:].
Common errors
- Unintended aliasing. Writing
b = aand then changingbchangesawhen the object is mutable. Copy explicitly if you need independence. - Using
isfor value comparison. The result is unreliable for numbers and strings. Use==. - Using
==forNone. It usually works, butis Noneis the standard form, and a custom type may define==in a surprising way. - Assuming a shallow copy is independent. Nested mutable objects are still shared. Use
copy.deepcopywhen you need to change nested data safely. - Expecting an immutable object to change. Calling a method on a string or adding to a number never changes the original. You must use the returned value.
Exercises
Exercise
What does this code print, and why? p = [1, 2] q = p p = p + [3] q += [4] print(p, q)
Show answer
It prints [1, 2, 3] [1, 2, 4]. The expression p + [3] builds a new list and rebinds p, so p and q no longer share an object. Then q += [4] mutates the list that q still refers to, which is the original [1, 2]. That list becomes [1, 2, 4], and p is unaffected.
Exercise
Given grid = [[0, 0], [0, 0]] and snapshot = grid.copy(), what does grid[0][0] = 1 do to snapshot? How would you make snapshot unaffected?
Show answer
snapshot also shows the change, [[1, 0], [0, 0]], because copy() makes a shallow copy and both outer lists hold the same inner lists. Use snapshot = copy.deepcopy(grid) after import copy to make the inner lists independent.