Concept #24Mediumpython-for-gen-ai

What's the difference between == and is in Python?

#gen-ai#python

Answer

text
==
vs
text
is
in Python

The Difference

  • text
    ==
    tests value equality — do the two objects have the same value?
  • text
    is
    tests identity — are the two variables pointing to the exact same object in memory?
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # True  — same value
print(a is b)   # False — different objects in memory
print(a is c)   # True  — same object (c is an alias for a)
print(id(a), id(b), id(c))  # a and c have same id; b is different

How Python Memory Works

python
# Python caches small integers (-5 to 256) and short strings
x = 256
y = 256
print(x is y)   # True  — same cached object

x = 257
y = 257
print(x is y)   # False — different objects (outside cache range)

# String interning
s1 = "hello"
s2 = "hello"
print(s1 is s2)  # True  — Python interns short strings

The
text
None
Special Case

Always use

text
is
to check for
text
None
:

python
# ✅ Correct
if result is None:
    return default_value

if result is not None:
    process(result)

# ❌ Wrong — an object could override __eq__ to equal None
if result == None:
    pass

Relevance in Gen AI Code

python
# Checking if an LLM response has content
response = client.chat.completions.create(...)
content = response.choices[0].message.content

# ✅ Check for None with 'is'
if content is None:
    raise ValueError("LLM returned no content")

# Checking model type identity
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic

model = ChatOpenAI()
print(type(model) is ChatOpenAI)   # True  — exact type check
print(isinstance(model, ChatOpenAI))  # True — also checks subclasses (preferred)

# Singleton pattern check for shared resources
_embedding_model = None

def get_embedding_model():
    global _embedding_model
    if _embedding_model is None:  # Correct: 'is None' for singletons
        _embedding_model = load_model()
    return _embedding_model

Quick Reference

ExpressionChecksUse When
text
a == b
Value equality (calls
text
__eq__
)
Comparing data values
text
a is b
Object identity (same memory)Checking
text
None
, singletons, type identity
text
a is None
Is it the None object?Always prefer over
text
== None
text
a is not None
Is it anything but None?Guard clauses, optional parameters
text
isinstance(a, T)
Is
text
a
an instance of
text
T
or subclass?
Type checking (better than
text
type() is
)

Gotcha: Never use

text
is
to compare strings, lists, numbers, or other values in your logic. It works by accident for small integers and interned strings, but will silently fail for other values. Reserve
text
is
exclusively for
text
None
and identity checks.