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
| Operator | Asks | Example |
|---|---|---|
| == | Same value? | [1] == [1] → True |
| is | Same object? | [1] is [1] → False |
| in | Is it inside? | 'a' in 'cat' → True |
| not in | Is it absent? | 5 not in [1, 2] → True |
In code
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
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