There’s a subtle difference between the Python identity operator (
is) and the equality operator (
==). Your code can run fine when you use the Python
is operator to compare numbers, until it suddenly doesn’t. You might have heard somewhere that the Python
is operator is faster than the
== operator, or you may feel that it looks more Pythonic. However, it’s crucial to keep in mind that these operators don’t behave quite the same.
== operator compares the value or equality of two objects, whereas the Python
is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators
!=, except when you’re comparing to
In this tutorial, you’ll learn:
- What the difference is between object equality and identity
- When to use equality and identity operators to compare objects
- What these Python operators do under the hood
- Why using
is notto compare values leads to unexpected behavior
- How to write a custom
__eq__()class method to define equality operator behavior
Python Pit Stop: This tutorial is a quick and practical way to find the info you need, so you’ll be back to your project in no time!
Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Comparing Identity With the Python is and is not Operators
is not operators compare the identity of two objects. In CPython, this is their memory address. Everything in Python is an object, and each object is stored at a specific memory location. The Python
is not operators check whether two variables refer to the same object in memory.
Note: Keep in mind that objects with the same value are usually stored at separate memory addresses.
You can use
id() to check the identity of an object:
>>> help(id) Help on built-in function id in module builtins: id(obj, /) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.) >>> id(id) 2570892442576
The last line shows the memory address where the built-in function
id itself is stored.
There are some common cases where objects with the same value will have the same id by default. For example, the numbers -5 to 256 are interned in CPython. Each number is stored at a singular and fixed place in memory, which saves memory for commonly-used integers.
Join us and get access to hundreds of tutorials and a community of expert Pythonistas.
Already a member? Sign-In