Difference between is and equal in Python
In Python, there are two operators for determining equality: is
and ==
; however, what are the differences between them and when should one be used over the other?
What is the difference between the is
and ==
- The
is
operator checks for object identity - The
==
operator checks for equality
Here is an example demonstrating the differences:
1foo = [1, 2, 3]
2bar = foo
3print(foo is bar) # True
4print(foo == bar) # True
In the example above, bar
points to the same object reference as foo
. Because foo
and bar
point to the same object, is
reports true.
If a copy of foo
’s list is assigned to bar
,
1bar = foo[:]
2print(foo is bar) # False
3print(foo == bar) # True
is
reports False
since the two variables do not point to the same object.
When to use which?
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:
None
.
As stated in the PEP 8 style guide,
Comparisons to singletons like None should always be done with
is
oris not
, never the equality operators.
Outside of those two use cases, default to using the ==
or !=
operators.