Computer Science · Ch 5 — Getting Started with Python
Identity Operators
Identity Operators
Identity operators answer a different question from the equality operator ==. Instead of asking "do these two values look the same?", they ask "is the value of a variable of a certain type?" and, more generally, "are these two variables referring to the very same object in memory?"
Recall from Section 5.6 that every object in Python has a unique identity (ID), returned by the id() function, which stays the same for the object's lifetime. Identity operators compare exactly these IDs.
There are two identity operators: is and is not.
The is operator
var1 is var2 evaluates to True if the variables on either side of the operator point to the same memory location, and False otherwise. Equivalently: var1 is var2 results in True if id(var1) is equal to id(var2).
A first use is checking the type of a value:
>>> num1 = 5
>>> type(num1) is int
True
A second use is checking whether two names share one object. When we assign one variable to another, Python copies only the reference, so both names point to the same object and their IDs match:
>>> num1 = 5
>>> num2 = num1
>>> id(num1)
1433920576
>>> id(num2)
1433920576
>>> num1 is num2
True
Both id() calls print the same identity, so num1 is num2 is True.
The is not operator
var1 is not var2 is the opposite test: it evaluates to False if the variables on either side point to the same memory location, and True otherwise. Equivalently: var1 is not var2 results in True if id(var1) is not equal to id(var2).
Continuing the example above:
>>> num1 is not num2
False
Since num1 and num2 refer to the same object, "is not the same object" is False.
Quick reference
| Operator | Evaluates to True when… |
|---|---|
is | both variables point to the same memory location — id(var1) equals id(var2) |
| Operator | Description | Example (Try in Lab) |
|---|---|---|
| is | Evaluates True if the variables on either side of the operator point towards the same memory location and False otherwise. var1 is var2 results to True if id(var1) is equal to id(var2) | >>> num1 = 5 >>> type(num1) is int True >>> num2 = num1 >>> id(num1) 1433920576 >>> id(num2) 1433920576 >>> num1 is num2 True |