Python Object Comparison : "is" vs "=="

Python Object Comparison : "is" vs "=="

In Python, both "is" and "==" are used to compare objects, but they serve different purposes and operate in distinct ways.

  1. "==" (Equality Operator):

    • Compares the values of two objects.
    • Invokes the __eq__ method of an object, which means you can define the behavior of the equality operator for custom objects by overriding the __eq__ method.
    • Returns True if the objects have the same value, and False otherwise.

    Example:

    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    print(list1 == list2)  # True, because the lists have the same content
    
  2. "is" (Identity Operator):

    • Compares the identities of two objects.
    • Returns True if both references point to the same object (same memory location), and False otherwise.
    • It's effectively comparing the id() of the objects.

    Example:

    list1 = [1, 2, 3]
    list2 = list1  # list2 now references the same object as list1
    
    print(list1 is list2)  # True, because both lists reference the same memory location
    

Here's a combined example to showcase the difference:

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2)  # True, because values are the same
print(list1 is list2)  # False, because they are two different objects in memory

print(list1 == list3)  # True, because values are the same
print(list1 is list3)  # True, because both point to the same memory location

In general:

  • Use "==" when you want to check if two objects are equivalent in value.
  • Use "is" when you want to check if two references point to the same object in memory (e.g., checking if a variable is None because there's only one None object in Python: if variable is None).

More Tags

element linux dialogflow-es heroku android-lifecycle addition hibernate-spatial android-popupwindow angularjs-filter uipinchgesturerecognizer

More Programming Guides

Other Guides

More Programming Examples