πŸ†” Python Identity Operators β€” Checking Object Identity

Introduction 🌟

Identity operators are used to compare the **memory location** of two objects. Instead of checking if two values are equal, identity operators check whether the variables refer to the **same object** in memory.

Note

πŸ’‘ Identity operators check *object identity*, not value equality.

1. List of Identity Operators πŸ“‹

OperatorMeaningExample
isTrue if both variables reference the same objectx is y
is notTrue if variables reference different objectsx is not y

2. Using the "is" Operator πŸ”

is checks whether two variables point to the exact same object (same memory address).

is_operator.py

x = 10
y = 10

print(x is y)      # True (small integers are cached)
print(x == y)      # True (same value)

Note

βœ”οΈ x is y checks identity
βœ”οΈ x == y checks value
These are NOT the same!

3. Using the "is not" Operator 🚫

Returns True if the variables reference different objects.

is_not_operator.py

a = ["apple", "banana"]
b = ["apple", "banana"]

print(a == b)        # True (same content)
print(a is b)        # False (different objects)
print(a is not b)    # True

Note

🧠 Lists, strings, and other collections create **new objects**, so identity comparisons often return False even if values match.

4. Identity Operators vs Equality Operators βš–οΈ

OperatorChecksExample
==Value equality[1, 2] == [1, 2] β†’ True
isObject identity (same memory)[1, 2] is [1, 2] β†’ False

Note

πŸ”₯ Always use == to compare values, and is to check if two references point to the same object.

5. Identity With Mutable vs Immutable Types 🧠

Immutable types (int, float, str, tuple)

Python often reuses small immutable objects, so identity checks may return True.

immutable_identity.py

x = "hello"
y = "hello"

print(x is y)   # True (string interning)

Mutable types (list, dict, set)

Mutable types always create new objects β†’ identity is usually False.

mutable_identity.py

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

print(a == b)  # True
print(a is b)  # False

6. Checking None With Identity Operators 🟒

The preferred way to compare with None is using is, not ==.

none_check.py

value = None

if value is None:
    print("Value is None")

if value is not None:
    print("Value is not None")

Note

βœ”οΈ is None is considered best practice in Python.

7. Real-World Example 🌍

real_world.py

# check if caching applied
x = 256
y = 256

print(x is y)   # True (caching)

x = 257
y = 257
print(x is y)   # False (new objects)

Conclusion πŸŽ‰

>>β€œIdentity operators reveal whether two variables share the same existence β€” not just the same value.” ✨

You now understand how Python identity operators work! Want the next tutorial on Membership Operators, Conditional Statements, Loops, or Control Flow? Just tell me! 😊