In Python, the meaning of "equal" can have different interpretations, and you use them according to the specific situation==oris. They have different uses and meanings:
==(equality operator):
- Used to compare whether the values of two objects are equal.
- It calls the object's
__eq__method (if that method is defined). - Suitable for comparing whether the content of numbers, strings, lists, etc. is the same.
Example
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Output: True, because the contents of a and b are the same
b = [1, 2, 3]
print(a == b) # Output: True, because the contents of a and b are the same
is(identity operator):
- Used to compare whether the identities of two objects are the same, that is, whether the addresses of the two objects in memory are the same.
- Only when two variables reference the same object,
iswill it return True.
Example
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # Output: False, because a and b are different objects, even though their contents are the same
print(a is c) # Output: True, because c and a reference the same object
b = [1, 2, 3]
c = a
print(a is b) # Output: False, because a and b are different objects, even though their contents are the same
print(a is c) # Output: True, because c and a reference the same object
Summary:
- Use
==to check whether the values of two objects are equal. - Use
isto check whether two objects are the same instance (that is, whether their addresses in memory are the same).
For example:
Example
# Numeric comparison
x = 10
y = 10
print(x == y) # Output: True
print(x is y) # Output: True, because Python caches small integer objects; x and y are actually the same object
# String comparison
a = "hello"
b = "hello"
print(a == b) # Output: True
print(a is b) # Output: True, because short strings are cached
# List comparison
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # Output: True
print(list1 is list2) # Output: False, because list1 and list2 are different objects
# None comparison
c = None
d = None
print(c == d) # Output: True
print(c is d) # Output: True, because None is a singleton
x = 10
y = 10
print(x == y) # Output: True
print(x is y) # Output: True, because Python caches small integer objects; x and y are actually the same object
# String comparison
a = "hello"
b = "hello"
print(a == b) # Output: True
print(a is b) # Output: True, because short strings are cached
# List comparison
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # Output: True
print(list1 is list2) # Output: False, because list1 and list2 are different objects
# None comparison
c = None
d = None
print(c == d) # Output: True
print(c is d) # Output: True, because None is a singleton