Sobes.tech
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 == b returns True if the objects are equal in content.
  • By reference (identity):

    • The is operator is used, which checks whether the variables point to the same object in memory.
    • Example: a is b returns True if a and b are the same object.

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.