I. Overview of Identity and Equality Operations
In Python, both is and == can be used to compare two objects, but they check completely different things.
is: the identity operator, which checks whether two references point to the same object.==: the equality operator, which checks whether the values of two objects are equal.
For example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
Although the two lists have exactly the same contents, they are two independently created objects.
Look at another example:
a = [1, 2, 3]
b = a
print(a == b) # True
print(a is b) # True
Here, b = a does not create a new list; instead, it makes both variables reference the same object.
1. Core Differences
| Comparison dimension | is |
== |
|---|---|---|
| Operation name | Identity operation | Equality operation |
| What it checks | Whether they are the same object | Whether values are equal |
| Basis of comparison | Object identity | Equality semantics |
| Customizable | Cannot be overloaded | Can be customized via __eq__() |
| Return result | bool |
Usually bool, but may be another object |
| Typical use | Checking for None or sentinel objects |
Comparing numeric values, strings, or container contents |
Keep this in mind:
Objects that are the same are definitely equal; equal objects are not necessarily the same.
The “definitely equal” here is based on the normal Python object identity and equality protocols. Custom classes can implement nonstandard equality rules, but comparing the same object with itself should usually still satisfy a reasonable reflexive design.
II. Python Object Model and Identity
1. Variables Are Not the Objects Themselves
To understand is and ==, you first need to understand Python’s object model.
In Python, a variable name can be understood as a reference name for an object. A variable is bound to an object, rather than directly representing a value in a fixed memory slot as in the intuitive model of some statically typed languages.
For example:
a = 100
b = a
This can be understood as:
variable a ──┐
├──> integer object 100
variable b ──┘
At this point, a and b reference the same object.
Now consider:
a = [1, 2, 3]
b = [1, 2, 3]
This can be understood as:
variable a ─────> list object A [1, 2, 3]
variable b ─────> list object B [1, 2, 3]
The two objects have the same contents, but different identities.
2. What Is Object Identity?
Object identity represents a unique identifier for an object during its lifetime.
Python provides the built-in function id() to obtain an object’s identity identifier:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(id(a))
print(id(b))
print(id(c))
You can usually observe:
id(a) == id(c) # True
id(a) == id(b) # False
In CPython, id() is usually related to the object’s memory address during its lifetime, but this is an implementation detail and should not be generalized as a guarantee for all Python implementations.
At the language level, Python guarantees the following:
- For the same object during its lifetime, the value returned by
id()remains unchanged. - At any given moment, different live objects have different identity identifiers.
- After an object is destroyed, its identity identifier may be reused by objects created later.
Therefore, id() should not be treated as a permanent unique ID, a database primary key, or a cross-process object identifier.
3. Relationship Between is and id
For two objects that are both alive at the same time:
a is b
and:
id(a) == id(b)
are equivalent in terms of identity-checking semantics.
However, in practical programming, you should prefer is:
if a is b:
print("两个变量引用同一个对象")
rather than:
if id(a) == id(b):
print("两个变量引用同一个对象")
The reason is that is directly expresses the intent of an object identity check; it is more concise, and it avoids mistakenly relying on identity numbers when an object's lifetime changes.
III. The Identity Operator is
1. Basic Syntax
a is b
If both operands reference the same object, it returns True; otherwise it returns False.
a = [10, 20]
b = a
c = [10, 20]
print(a is b) # True
print(a is c) # False
2. The is not Operator
is not is used to determine whether two objects are not the same object.
a = [1, 2]
b = [1, 2]
c = a
print(a is not b) # True
print(a is not c) # False
is not and is are logical opposites of each other as identity checks.
3. is Does Not Compare Object Contents
a = {"name": "Alice"}
b = {"name": "Alice"}
print(a == b) # True
print(a is b) # False
Even if a dictionary's keys and values are completely identical, that does not mean they are the same object.
4. is Cannot Be Overloaded
Python's identity operators are built-in language operations; their behavior cannot be changed by defining __is__() or __isnot__().
For example:
class Example:
def __eq__(self, other):
return True
a = Example()
b = Example()
print(a == b) # True
print(a is b) # False
Even with a custom equality rule, is still judges by object identity.
IV. The Equality Operator ==
1. Basic Syntax
a == b
Used to determine whether two objects are equal.
a = 100
b = 100
print(a == b) # True
For built-in types, equality operations generally follow the value semantics defined by that type.
For example:
print(10 == 10) # True
print("Python" == "Python") # True
print([1, 2] == [1, 2]) # True
print({"a": 1} == {"a": 1}) # True
print((1, 2) == (1, 2)) # True
2. Different Objects Can Be Equal
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
This is precisely the most important difference between the equality operation and the identity operation.
3. Equality Does Not Mean the Types Must Be Exactly the Same
In Python, some objects of different types can also compare as equal.
print(1 == 1.0) # True
print(True == 1) # True
print(False == 0) # True
The reasons include:
intandfloatcan be compared by numeric value in numeric comparisons.boolis a subclass ofint.- Python's equality rules allow different types to implement cross-type comparisons.
But whether the types are the same cannot be determined simply through ==.
If the business requirement is that the types must also match, you can check both at once:
a = 1
b = True
print(type(a) is type(b)) # False
print(a == b) # True
You can also use:
if type(a) is type(b) and a == b:
print("类型和数值都相同")
Whether strict type checking is needed should be decided by the business semantics.
V. The Underlying Mechanism of ==: eq()
1. The Equality Protocol
Python's equality operation can be customized through the special method __eq__().
For example:
class User:
def __init__(self, user_id):
self.user_id = user_id
def __eq__(self, other):
if not isinstance(other, User):
return NotImplemented
return self.user_id == other.user_id
a = User(1001)
b = User(1001)
print(a == b) # True
print(a is b) # False
Although the two objects are not the same instance, because user_id is the same, they are considered equal according to the custom rule.
2. How Python executes ==
For:
a == b
Python handles this using the rich comparison protocol.
The general process includes:
- Try the appropriate type comparison method.
- If the right-hand type is a strict subclass of the left-hand type and provides an applicable reflected comparison implementation, the right-hand method may be tried first.
- If one side returns
NotImplemented, continue by trying the applicable method on the other side. - If neither side provides a usable comparison result, use the default fallback behavior.
For ordinary objects without custom equality behavior, default equality usually manifests as identity equality.
A typical comparison process can be summarized as:
flowchart TD
A["Execute a == b"] --> B["Enter rich comparison protocol"]
B --> C{"Is there an applicable comparison method?"}
C -->|Yes| D["Call __eq__ on the higher-priority side"]
C -->|No| G["Use default fallback rule"]
D --> E{"Does it return NotImplemented?"}
E -->|No| F["Use comparison result"]
E -->|Yes| H["Try the other side's comparison method"]
H --> I{"Is a valid result obtained?"}
I -->|Yes| F
I -->|No| G
G --> J["Execute default equality fallback"]
F --> K["Return comparison result"]
J --> K
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note: this describes a general process of the rich comparison protocol; it should not be understood as meaning that all objects always follow a fixed one-way call order.
3. The role of NotImplemented
In a custom comparison method, if it cannot handle another type, it can return NotImplemented.
class Product:
def __init__(self, price):
self.price = price
def __eq__(self, other):
if not isinstance(other, Product):
return NotImplemented
return self.price == other.price
a = Product(100)
b = Product(100)
print(a == b) # True
NotImplemented is a special built-in singleton used to indicate that the current operation method cannot handle the given operands.
It is not an exception, nor is it equivalent to NotImplementedError.
Do not write:
def __eq__(self, other):
if not isinstance(other, Product):
return False
In some designs, this terminates the comparison logic that the other side might support too early.
4. eq does not necessarily return bool
Python's rich comparison methods are allowed to return non-boolean objects.
class Example:
def __eq__(self, other):
return "equal"
a = Example()
b = Example()
result = a == b
print(result) # equal
print(type(result)) # <class 'str'>
This means:
a == b
does not guarantee that it will necessarily produce a genuine bool object.
However, in conditional expressions, Python performs a truth-value evaluation on the result:
if a == b:
print("条件成立")
In engineering practice, it is usually recommended that a custom __eq__() return an explicit Boolean value to avoid confusing comparison results.
6. Equality Rules for Different Data Types
1. Numeric Types
Numeric types are typically compared by numeric value:
print(10 == 10) # True
print(10 == 10.0) # True
print(1 + 0j == 1) # True
print(True == 1) # True
Floating-point comparisons require special attention to precision issues:
a = 0.1 + 0.2
b = 0.3
print(a == b) # False
This is because binary floating-point numbers cannot exactly represent some decimal fractions.
For scenarios that require tolerance-based comparison, you can use math.isclose():
import math
a = 0.1 + 0.2
b = 0.3
print(math.isclose(a, b)) # True
You can also specify relative and absolute tolerances:
print(
math.isclose(
a,
b,
rel_tol=1e-9,
abs_tol=1e-12
)
)
Note that complex numbers can be compared for equality and inequality, but do not support ordering comparisons.
2. Strings
Strings are compared based on the content of their character sequence:
a = "Python"
b = "Python"
c = "python"
print(a == b) # True
print(a == c) # False
String equality comparison is case-sensitive.
In addition, characters that look the same in Unicode may have different underlying encoding sequences.
For example, some accented characters can be represented by a single precomposed code point or by a base character followed by a combining mark.
In such cases, using == directly may return False.
If your business logic needs to compare after Unicode normalization, you can use unicodedata.normalize():
import unicodedata
a = "\u00e9"
b = "e\u0301"
print(a == b) # False
a_normalized = unicodedata.normalize("NFC", a)
b_normalized = unicodedata.normalize("NFC", b)
print(a_normalized == b_normalized) # True
3. Lists
Lists are compared item by item in element order.
a = [1, 2, 3]
b = [1, 2, 3]
c = [3, 2, 1]
print(a == b) # True
print(a == c) # False
List equality requires:
- The same length.
- Elements at corresponding positions are equal.
Nested objects within lists also participate in equality comparison.
a = [[1, 2], [3, 4]]
b = [[1, 2], [3, 4]]
print(a == b) # True
4. Tuples
Tuples are similar to lists and are also compared in element order.
a = (1, 2, 3)
b = (1, 2, 3)
print(a == b) # True
However, if a tuple contains mutable objects, it may still be affected by changes in the state of those objects.
5. Dictionaries
Dictionary equality is determined primarily by the key-value mapping relationship and is independent of insertion order.
a = {"name": "Alice", "age": 25}
b = {"age": 25, "name": "Alice"}
print(a == b) # True
As long as the key-value mappings are the same, dictionaries are generally equal.
6. Sets
Set equality does not consider element order:
a = {1, 2, 3}
b = {3, 2, 1}
print(a == b) # True
Set comparison focuses on whether the elements are the same, not on their order.
7. Custom Objects
Custom objects usually use identity semantics for equality comparison by default:
class User:
pass
a = User()
b = User()
c = a
print(a == b) # False
print(a == c) # True
If you want objects to be compared by business fields, you need to implement __eq__().
VII. Common Phenomena with Object Caching and is
1. Why Small Integers May Be is True
Observe the following code:
a = 10
b = 10
print(a == b) # True
print(a is b) # may be True
In some environments, two variables may refer to the same integer object.
This is because Python implementations may cache or reuse some immutable objects.
In CPython, common small integers are usually cached.
But note carefully:
Integer caching is an implementation detail, not a guarantee of is at the Python language level.
Do not use is to determine whether integers are equal.
Correct way:
a = 1000
b = 1000
print(a == b)
2. Why Strings May Be is True
Strings may also be interned.
a = "python"
b = "python"
print(a == b) # True
print(a is b) # may be True
Some strings may be reused by the interpreter, causing different variables to refer to the same object.
However, whether a string is interned depends on the interpreter implementation, compilation context, and the specific string.
Do not rely on string interning behavior for identity checks.
3. Do Not Use is to Compare Ordinary Numeric Values
Incorrect example:
number = 1000
if number is 1000:
print("相等")
Correct example:
number = 1000
if number == 1000:
print("相等")
4. Do Not Use is to Compare Ordinary Strings
Incorrect example:
name = "Python"
if name is "Python":
print("匹配")
Correct example:
name = "Python"
if name == "Python":
print("匹配")
5. Caching Behavior and Object Lifetime
A Python object's identity is valid only for its lifetime.
After an object is destroyed, its identity number may be reused by a later object.
Therefore:
id(a)
It should not be treated as a permanent unique identifier for an object.
If a stable identifier is needed, use a business ID, UUID, or another explicit identification mechanism.
VIII. Why None Should Be Checked Using is
1. None Is a Singleton Object
In Python, None is a special singleton object.
All None in a program refer to the same object.
Therefore, to determine whether a variable is None, the recommended form is:
value = None
if value is None:
print("没有值")
You can also use:
if value is not None:
print("存在有效对象")
2. Why == None Is Not Recommended
Although the following form usually works:
if value == None:
print("没有值")
However, the preferred form is:
if value is None:
print("没有值")
The reason is that == can be overloaded by custom classes.
For example:
class Strange:
def __eq__(self, other):
return other is None
value = Strange()
print(value == None) # True
print(value is None) # False
Here, value is not None; its equality rule simply considers itself equal to None.
Therefore, identity operators should be used to check whether something is None.
3. Engineering Conventions for None Checks
Recommended:
if value is None:
...
Recommended:
if value is not None:
...
Not recommended:
if value == None:
...
Not recommended:
if value is not None:
...
The last example is itself correct; what should actually be avoided is mistakenly replacing is not with !=, especially when strict identity semantics are required.
9. is with Mutable and Immutable Objects
1. Immutable Objects
Once an immutable object is created, its internal value cannot be modified in place.
Common immutable types include:
intfloatboolstrtuple(but it may contain mutable objects)frozensetbytes
Example:
a = 100
b = a
b = 200
print(a) # 100
print(b) # 200
Here, the integer object is not modified; instead, b is rebound to another integer object.
2. Mutable Objects
Mutable objects can have their contents modified on the original object.
Common mutable types include:
listdictsetbytearray
Example:
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]
print(a is b) # True
Because both variables reference the same list, modifying the object through one variable is also observed through the other.