← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 14 of 16

Python Identity Operators

What Is Identity?

Every object in Python lives at a specific memory address, and identity means checking whether two variable names point to that exact same object rather than just holding equal-looking values. The built-in id() function returns a number representing that address, and Python's is operator compares those addresses directly.

Example: What Is Identity?

python
a = [1, 2]
b = [1, 2]
print(id(a) == id(b))
print(a is b)

is and is not

The is operator returns True only when both operands are literally the same object in memory, while is not is its negation. This is different from ==, which asks whether two objects have equal value even if they're stored separately — two different list objects with identical contents are equal but not identical.

Example: is and is not

python
a = [1, 2]
b = a
c = [1, 2]
print(a is b)
print(a is not c)

is vs == in Practice

Use == when you care about value equality, like comparing two strings or numbers for content, and reserve is for identity checks such as x is None, which is the idiomatic and recommended way to test for None specifically. Using == for None comparisons can misbehave with custom classes that override equality.

Example: is vs == in Practice

python
x = None
print(x is None)
print(x == None)

The Small Integer Cache Gotcha

CPython caches small integers (typically -5 to 256) and short strings as singleton objects for performance, so a = 5; b = 5; a is b often returns True by coincidence, not by design. Relying on is for general value comparison is a common bug source because this caching behavior isn't guaranteed by the language spec and can vary.

Example: The Small Integer Cache Gotcha

python
a = 5
b = 5
print(a is b)  # True due to CPython's small-int caching, not guaranteed behavior

Practical Identity Checks

Identity checks are most useful for sentinel values, singleton comparisons like is None or is True, and verifying whether two variables reference the exact same mutable object before deciding whether modifying one will affect the other. This matters especially when passing mutable objects like lists between functions.

Example: Practical Identity Checks

python
def process(items=None):
    if items is None:
        items = []
    return items

a = process()
b = process()
print(a is b)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.