The is
operator in Python is used to compare the object identity of two variables.
Key Points:
-
Object Identity vs. Equality:
is
checks if two variables refer to the same object in memory.==
checks if the values of two objects are equal.
-
Example:
Python
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y) # Output: True (x and y refer to the same list object)
print(x is z) # Output: False (x and z refer to different list objects, even though their values are the same)
print(x == y) # Output: True (x and y have the same values)
print(x == z) # Output: True (x and z have the same values)
-
When to Use
is
:- Comparing Singletons:
None
,True
, andFalse
are singletons in Python.- Use
is
to compare them:if x is None: ...
- Checking for the Same Object:
- When you specifically need to ensure two variables point to the exact same object in memory.
- Comparing Singletons:
-
Important Notes:
is
can sometimes be less predictable with mutable objects like lists.- For most comparisons,
==
is generally preferred.
In Summary:
- Use
is
when you need to know if two variables refer to the same object in memory. - Use
==
when you need to know if two objects have the same value.
0 件のコメント:
コメントを投稿