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 (
==
) returnsTrue
if two objects have the same value, otherwiseFalse
.
is
Operator
The identity operators (is
, is not
) compare objects based on their identity.
is
operator returnsTrue
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 usingid()
:list1 = [] list2 = [] print(id(list1)) print(id(list2))
- Note: We can find the
- Otherwise, it returns
False