Comparing the == and is Python Operators

Content:

Along with the == operator common in many programming languages, Python also includes an is operator which can be used for comparisons.

It’s often unclear which operator should be used, with many examples of the less optimal operator being employed by mistake.

This article will explain the difference between the two operators, and show you when each of the two should be used.

The is Operator

The is (and the opposing is not) operator is an example of an identity operator. It’s intended to compare objects based on their identity. That is, the operator returns true when the two objects being compared share the same memory location. In this case, they literally are the same object.

The == Operator

This probably doesn’t need an introduction, but we’ll explain it for newcomers to the language. == compares the values on either side of the operator. The values can reside anywhere in memory, and can be physically two separate objects that are set to hold the came value.

When to Use Each Operator

Most of the time, you’ll want to use ==. Comparing by value is a common requirement in any computer program. It’s very rare that you’ll want to compare two objects directly (using is), unless you’re dealing with complex data structures.

One exception to this is when trying to compare a value to the built-in Python None object, which is used to define a null value.

x = getData()  # Fetch some data

if (x is None):
    print("No data was returned")

You might want to check whether your value is equal to None to determine whether a valid value has been set. This is demonstrated in the code block above.

If you like what we do, consider supporting us on Ko-fi