Junior — Middle
What methods can be used to determine if two objects in Python are equal by content or by reference?
sobes.tech AI
Answer from AI
In Python, different methods are used to compare two objects by content and by reference:
-
By content (value):
- The
==operator is used, which calls the__eq__method of objects. - Example:
a == breturnsTrueif the objects are equal in content.
- The
-
By reference (identity):
- The
isoperator is used, which checks whether the variables point to the same object in memory. - Example:
a is breturnsTrueifaandbare the same object.
- The
Example:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # True, contents are the same
print(list1 is list2) # False, different objects
print(list1 is list3) # True, same reference
Thus, == checks for equality of content, while is checks for reference equality.