Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The is operator in Python is an object identity operator. It evaluates whether two variables reference the exact same object in memory, rather than checking if their underlying values are equivalent. When the is operator is invoked, Python compares the memory addresses of the operands. Under the hood, the expression a is b is functionally equivalent to evaluating id(a) == id(b), where the CPython id() function returns the integer representation of an object’s memory address.
expression_1 is expression_2
expression_1 is not expression_2

Identity vs. Equality

The distinction between is (identity) and == (equality) is a fundamental mechanic in Python’s memory management. Two distinct objects can hold identical data, satisfying the == operator, while failing the is operator because they occupy different memory locations.

# Two distinct list objects allocated in memory with identical values
list_a = [1, 2, 3]
list_b = [1, 2, 3]


# Equality (==) evaluates to True because the data matches
print(list_a == list_b)  # Output: True


# Identity (is) evaluates to False because they are different objects in memory
print(list_a is list_b)  # Output: False


# Assigning list_a to list_c copies the memory reference, not the object itself
list_c = list_a
print(list_a is list_c)  # Output: True

CPython Interning and Singletons

The evaluation of the is operator is heavily influenced by CPython’s memory optimization techniques, specifically object interning. CPython pre-allocates and caches certain immutable objects as singletons to save memory. When variables are assigned these specific values, Python points them to the same cached memory address.
  1. Small Integers: CPython caches integers in the range of -5 to 256.
  2. Strings: String literals containing only ASCII letters, digits, or underscores are typically interned.
  3. Built-in Constants: None, True, and False are strict singletons.

# 100 falls within the cached integer range (-5 to 256)
x = 100
y = 100
print(x is y)  # Output: True


# 1000 falls outside the cached range, resulting in distinct object allocations
a = 1000
b = 1000
print(a is b)  # Output: False (Note: Behavior may vary depending on compiler optimizations in scripts vs REPL)
Master Python with Deep Grasping Methodology!Learn More