Testing identity

Author

Clayton Cafiero

Published

2025-06-06

Identity and equivalence

Identity and equivalence aren’t the same thing. Here’s a simple example:

>>> a = 12345678987654321
>>> b = 12345678987654321
>>> a == b
True

So far, this is exactly what we’d expect: a and b certainly have the same value.

Python provides the keyword is to test for identity—asking if two things are actually the same object going by different names.

>>> a is b
False

Python is telling us that despite a and b having the exact same value, they are, in fact two different objects. In other words, the value of a is equivalent to the value of b, but a and b refer to different objects.

Let’s check.

>>> id(a)
4312275152
>>> id(b)
4312270928

Yup. They have different ids (if you try this on your computer you’ll get different ids, but the id for a will differ from the id for b).

Let’s check another way.

>>> a = 5
>>> b
12345678987654321

Yup. We’ve changed the value of a and the value of b remains unchanged. Clearly these are different objects.

Let’s see an example of two identifiers referring to the same object.

>>> a = 12345678987654321
>>> b = a
>>> a is b
True
>>> b is a
True

In this instance, a and b are different names for the same object. Let’s check their ids.

>>> id(a)
4312271472
>>> id(b)
4312271472

Yup. They’re exactly the same.

When is this useful? Sometimes we want to know whether two names refer to the same object. We’ll see some interesting examples when we learn about mutability in Chapter 10. For now, the most common use of is is to check for None in a conditional.

If you recall, None is a special value in Python which means “no value” (I know, it’s a little odd having an object that has a value which means “no value”, but there you have it). There are never multiple copies of None. None is a singular object.

>>> a = None
>>> b = 42
>>> b = None
>>> c = None
>>> d = None
>>> a == b == c == d   # This is true,...
True
>>> a is b is c is d   # but this is more important.
True

All these variables are just different names for the same object, the singular object None. Accordingly, the best practice when checking for None isn’t to use the comparison operator (==) but rather the identity keyword is.

if x is None:
    print("x has no value")

Copyright © 2023–2025 Clayton Cafiero

No generative AI was used in producing this material. This was written the old-fashioned way.