Identity Operators

Identity operators in Python are used to compare the memory location (identity) of objects, not just their values. They answer the question:
Do both variables refer to the same object in memory?
Python provides two identity operators:
  • is
  • is not

What Are Identity Operators?

Identity operators check whether two variables point to the same object.
python
x = 10
y = 10

print(x is y)
python
print(x == y)
Both may look similar, but they are very different checks.

Identity Operators Table

OperatorDescription
isReturns True if both variables refer to the same object
is notReturns True if both variables refer to different objects

is vs == (Most Important Concept)

OperatorWhat it checks
==Value equality
isMemory identity

Example

python
a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
print(a is b)
Explanation:
  • == → values are equal
  • is → different objects in memory

Identity Operators with Immutable Types

Python may reuse memory for small immutable objects.
python
x = 10
y = 10

print(x is y)
python
a = "Python"
b = "Python"

print(a is b)
This happens due to interning.

Identity Operators with Mutable Types

Mutable objects usually do not share memory.
python
x = [1, 2, 3]
y = [1, 2, 3]

print(x is y)
python
print(x == y)

When Identity Becomes True for Mutable Objects

python
a = [1, 2]
b = a

print(a is b)
python
b.append(3)
print(a)
Both variables point to the same list.

Identity Operator with None (Best Practice)

The correct way to check for None is using is.
python
x = None

if x is None:
    print("x is None")
python
if x is not None:
    print("x has a value")

Why is Is Preferred for None

python
x = None
print(x == None)
print(x is None)
Using is avoids unexpected behavior.

Identity Operators with Functions

python
def func():
    pass

a = func
b = func

print(a is b)
Both refer to the same function object.

Identity Operators with Boolean Values

python
print(True is True)
python
print(False is False)
python
print(True is 1)
Explanation:
  • True == 1True
  • True is 1False

Identity Operators with Integers (Tricky)

python
a = 256
b = 256

print(a is b)
python
x = 1000
y = 1000

print(x is y)
Small integers may be cached; larger ones usually are not.

Common Mistakes

Mistake 1: Using is for value comparison

python
print(1000 is 1000)
Unreliable ❌
Correct:
python
print(1000 == 1000)

Mistake 2: Using == to check None

python
if x == None:
    pass
Correct:
python
if x is None:
    pass

Summary

  • Identity operators check memory location
  • is and is not are identity operators
  • == checks values, not identity
  • Use is for checking None
  • Immutable objects may share memory
  • Mutable objects usually don’t
  • Identity checks are important for debugging and correctness

Practice

  • Compare two lists using == and is
  • Assign one variable to another and test identity
  • Check a variable against None using is
  • Predict outputs of identity comparisons