Check if two variables point to the same object in memory using is
and is not
Identity operators compare the memory location of two objects.
Operator | Description | Example |
---|---|---|
is | True if both variables point to the same object | x is y |
is not | True if they point to different objects | x is not y |
a = [1, 2, 3]
b = a # Same object
c = [1, 2, 3] # Same content, different object
print(a is b) # True
print(a is c) # False
print(a == c) # True (compares value)
print(a is not c) # True
Python reuses small immutable objects (like integers and short strings), so is
may return True
for small values.
x = 100
y = 100
print(x is y) # True (small int caching)
x = 1000
y = 1000
print(x is y) # Might be False (large int)
value = None
if value is None:
print("No value provided")
if value is not None:
print("Processing value...")
is
and is not
only for identity comparisons (e.g., is None
).==
and !=
for value comparisons.is
with numbers or strings for equality — use ==
instead.