This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Object Identity

Using identity operators

face Josiah Wang

The is and is not operators are most commonly used to check whether an object is None (or not).

def add(numbers=None):
    if numbers is None:
        return None
    else:
        total = 0
        for number in numbers:
            total += number
        return total


result = add()
if result is not None:
    print(result)
else:
    print("Please provide an input.")

While you can technically use == for this purpose, PEP 8 recommends that you use is:

“Comparisons to singletons like None should always be done with is or is not, never the equality operators.”

This is because a programmer can always customise == and != (you will learn how to do this in the future), but will not be able to customise is/is not. Your code will produce a more consistent behaviour this way.

PEP 8 also warns that:

“beware of writing if x when you really mean if x is not None

The first checks whether x is True (or True-like). The second makes sure that x is not None.

And… final surprise… no quiz for this chapter!

There is really nothing else to add or practise. Most of the time, you will only use the identity operator to check whether an object is None.

But no fear, more quizzes will be coming your way in a bit! 😈