In Python, there are two operators for determining equality:
==; however, what are the differences between them and when should one be used over the other?
isoperator checks for object identity
==operator checks for equality
Here is an example demonstrating the differences:
In the example above,
bar points to the same object reference as
bar point to the same object,
is reports true.
If a copy of
foo’s list is assigned to
False since the two variables do not point to the same object.
As a general rule of thumb, use the
is operator for the following use-cases:
- Verify if two objects are the same object (not just the value)
- Comparison against constants:
As stated in the PEP 8 style guide,
Comparisons to singletons like None should always be done with
is not, never the equality operators.
Outside of those two use cases, default to using the