the full guide

Identity and membership operators

Identity operators (is, is not) check whether two names point to the very same object in memory. Membership operators (in, not in) check whether a value is present inside a collection.

6 min Intermediate

What you need: The earlier topics of this module.

Definition

Identity operators (is, is not) check whether two names point to the very same object in memory. Membership operators (in, not in) check whether a value is present inside a collection.

In simple words

Two people can own identical phones: == says they're equal, but is says they're not the same phone. And in is just asking: is this name on the guest list?

Why it matters

Using is where you meant == is a classic bug that works sometimes and fails later. And in on a set or dict is one of the fastest lookups in Python.

How it works

OperatorAsksExample
==Same value?[1] == [1] → True
isSame object?[1] is [1] → False
inIs it inside?'a' in 'cat' → True
not inIs it absent?5 not in [1, 2] → True

In code

identity.py
a = [1, 2]
b = [1, 2]
c = a

print(a == b)   # same value
print(a is b)   # different objects
print(a is c)   # same object

ages = {"Riya": 21, "Aman": 25}
print("Riya" in ages)   # checks the keys of a dict
print(21 in ages)
print("cat" in "education")

Output

True
False
True
True
False
True

Common mistakes

  • Writing if name is "Riya". Compare strings with ==.
  • Expecting in on a dict to check values. It checks keys. Use in d.values() for values.

Check yourself

Question 1

1. a = [1]; b = a. What is a is b?

Question 2

2. How should you check for None?

Summary

  • is checks identity, and == checks value.
  • in checks membership, and on a dict it checks keys.

Finished reading?

Sources: The Python Tutorial, python.org