Sub topic 10
Testing membership and identity: in, is, is None
This chapter assumes you can write a basic if statement, use comparison operators, and know that Python has lists, tuples, dicts, strings, and None. It covers three operators that often appear in conditions: in, is, and their negations not in and is not.
Membership with in
The in operator asks whether a value is found inside a container. It returns True or False, so you can use it directly as a condition.
x = 7
if x in (1, 3, 5, 7, 9):
print('odd single digit')Here in tests membership in a tuple. It is easier to read than the equivalent chain x == 1 or x == 3 or x == 5 ....
What "inside" means depends on the container:
| Container | What `in` checks | Example | Result |
|---|---|---|---|
| list, tuple | any element equal to the value | `3 in [1, 2, 3]` | `True` |
| string | a substring | `'ell' in 'hello'` | `True` |
| dict | a key, not a value | `'a' in {'a': 1}` | `True` |
| set | an element, using a fast hash lookup | `2 in {1, 2}` | `True` |
Use not in for the opposite test. It reads better than wrapping the whole test in not.
allowed = {'red', 'green', 'blue'}
color = 'purple'
if color not in allowed:
print('unsupported color')For repeated lookups in a large collection, prefer a set or a dict. A list must be scanned from the start, while a set finds the value in roughly constant time.
Identity with is
The == operator asks whether two values are equal. The is operator asks whether two names refer to the very same object in memory.
a = [1, 2]
b = [1, 2]
c = a
print(a == b) # True: same contents
print(a is b) # False: two separate lists
print(a is c) # True: c is another name for a's listTwo objects can be equal without being identical. This is why is is the wrong tool for comparing values.
Testing for None with is
None is a single object. Only one None exists in a running program, so the standard way to test for it is is None or is not None.
count = 0
if not count:
print('zero or missing')
if count is None:
print('missing')
else:
print('a number was provided')The first test is a truthiness check, so it treats 0 and None alike. The second test separates a missing value from a legitimate zero. Choose is None whenever 0, an empty string, or an empty list is a valid value.
def describe(limit=None):
if limit is None:
return 'no limit'
return f'limit is {limit}'
print(describe())
print(describe(0))This prints no limit and then limit is 0. A truthiness test such as if not limit: would wrongly report no limit for 0.
Common mistakes
- Using
isto compare numbers or strings, such asif name is 'admin':. It may appear to work because CPython reuses some small objects, but this is an implementation detail. Python 3.8 and later warn about it with aSyntaxWarning. Use==. - Writing
== None. It usually works, but a class can customize==, sois Noneis the safer and conventional form. - Expecting
inon a dict to search values. It checks keys only. Usevalue in d.values()for values. - Writing
if x == 1 or 2:. The2is always truthy, so the condition is always true. Writeif x in (1, 2):.
Exercise
A function receives timeout=None. Callers may pass 0 to mean "do not wait". Which test correctly detects that no timeout was given: if not timeout: or if timeout is None:? Explain why.
Show answer
Use if timeout is None:. The test not timeout is also true for 0, so it would treat a deliberate "do not wait" as a missing value. is None is true only when the argument was left out or set to None.