Python Difference between `==` and `is`

created:

updated:

tags: python

I’m recently going through a Java course, and there it mentions about equals() and == are not the same in Java. That reminded me of Python’s == and is and their difference, and I wanted to write down about it to remember better.

== Operator

The equality operator (==) compares objects based on their values. When it’s called, the object’s __eq__() class method gets called. The __eq__() class method may specify criteria to determine the equality.

  • Typically, the equality operator (==) returns True if two objects have the same value, otherwise False.

is Operator

The identity operators (is, is not) compare objects based on their identity.

  • is operator returns True if the variables on either side of the operator point at the same object (same memory location)
    • Note: We can find the id of Python objects by using id():
      list1 = []
      list2 = []
      print(id(list1))
      print(id(list2))
      
  • Otherwise, it returns False

References