isAdvanced Examples

Identity operator; tests whether two variables reference the same object

Identity and immutability

How Python optimizes identity for immutable objects.

python
import sys

# id() returns the memory address
a = "hello"
b = "hello"
print(f"id(a): {id(a)}")
print(f"id(b): {id(b)}")
print(f"Same id: {id(a) == id(b)}")
print(f"a is b: {a is b}")

# Mutable objects: never cached
a = [1, 2, 3]
b = [1, 2, 3]
print(f"\nLists - a is b: {a is b}")

# Tuples: sometimes cached
a = (1, 2, 3)
b = (1, 2, 3)
print(f"Tuples - a is b: {a is b}")

# Empty immutables are often singletons
print(f"() is (): {() is ()}")
print(f"'' is '': {'' is ''}")
print(f"0 is 0: {0 is 0}")
print(f"frozenset() is frozenset(): {frozenset() is frozenset()}")

CPython interns small integers, short strings, and some tuples. This is an implementation detail — never rely on it. Use 'is' only for documented singletons (None, True, False).

Want to try these examples interactively?

Open Advanced Playground