Andromeda
Note

Identity (Python)

Definition

Identity in Python refers to whether two variables point to the exact same object in memory, evaluated using the is operator.

Why It Matters

It is crucial for understanding mutability, memory allocation, and side-effects in Python code.

Core Concepts

list_a = [1, 2, 3]
list_b = list_a
list_c = [1, 2, 3]

print(list_a is list_b)  # True (Same object)
print(list_a is list_c)  # False (Different objects, same value)
print(id(list_a) == id(list_b)) # True
  • Equality (==): Asks, “Are the values inside these objects the same?” (e.g., [1, 2] == [1, 2] is True).
  • Identity (is): Asks, “Are these two variables pointing to the exact same memory address?” (e.g., [1, 2] is [1, 2] is False).
  • id() Function: Returns the unique integer identifier (memory address) of an object. If id(a) == id(b), then a is b.
  • Reference Copying: After b = a, b is a is True because both name tags point to the same object.

Connected Concepts