Sub topic 10
Testing membership and identity: in, is, is None
This chapter assumes you can write a basic if/elif/else chain, you know the comparison operators (==, <, and so on), and you know the built-in containers (list, tuple, set, dict, str) and None. The chapter covers three more operators that appear in conditions: in, is, and the idiom is None.
Membership: `in` and `not in`
The in operator asks whether a value is contained in a collection. It returns True or False, so it works directly as an if condition.
color = 'green'
if color in ('red', 'green', 'blue'):
print('primary color')
else:
print('something else')not in is the negation. Write x not in items, not not x in items. Both mean the same thing, but the first reads as one operator and is the form most style guides prefer.
What "contained" means for each type
The meaning of in depends on the type on the right-hand side.
| Right-hand side | What `in` checks | Example | Result |
|---|---|---|---|
| list, tuple | Any element equals the value | `3 in [1, 2, 3]` | `True` |
| set, frozenset | The value is an element (hash lookup) | `'a' in {'a', 'b'}` | `True` |
| dict | The value is a key | `'x' in {'x': 1}` | `True` |
| str | The value is a substring | `'cat' in 'concatenate'` | `True` |
| range | The value is in the range | `5 in range(0, 10)` | `True` |
Two details cause most of the surprises.
First, on a dict, in tests keys only. To test values, ask the values view explicitly.
prices = {'apple': 3, 'pear': 4}
print('apple' in prices) # True: a key
print(3 in prices) # False: 3 is a value, not a key
print(3 in prices.values()) # TrueSecond, on a string, in tests for a substring, not for a single element. 'ab' in 'xaby' is True. This is convenient for text, but it means 'a' in 'banana' and 'an' in 'banana' are both valid questions with different meanings.
Speed
Testing membership in a list or tuple scans element by element, so it takes time proportional to the length. Testing membership in a set or dict uses hashing and takes roughly constant time. For a short literal such as ('red', 'green', 'blue') the difference does not matter. If you test membership repeatedly against a large collection, build a set once.
allowed_ids = {101, 102, 103, 250, 999}
def can_enter(user_id):
if user_id in allowed_ids:
return True
return False
print(can_enter(250)) # True
print(can_enter(7)) # FalseSet elements and dict keys must be hashable. Testing an unhashable value against a set, such as [1] in {1, 2}, raises TypeError: unhashable type: 'list'.
Identity: `is` and `is not`
== asks whether two objects have equal values. is asks whether two names refer to the very same object in memory. These are different questions.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True: same contents
print(a is b) # False: two separate list objects
print(a is c) # True: c is another name for the same objectThink of a and b as two printed copies of the same document. They are equal, but they are not the same sheet of paper. c is a second label on the original sheet.
Why `is` is the wrong tool for values
Python may reuse objects for small integers and some strings, so is can appear to work on values and then fail on others. Whether two equal values share one object is an implementation detail that you cannot rely on.
x = 1000
y = 1000
print(x == y) # True, alwaysIf you wrote x is y here, the result could be True or False depending on how and where the numbers were created. Since Python 3.8, comparing a name to a literal with is (for example x is 1000) produces a SyntaxWarning for this reason. Use == for numbers, strings, and tuples of values. Reserve is for singletons, described next.
`is None`
None is a singleton: there is exactly one None object in a running program. That makes identity the precise test for it, and is None and is not None are the standard spellings.
result = None
if result is None:
print('no result yet')
else:
print('got', result)Prefer is None to == None for two reasons. It is guaranteed to give the right answer, because == can be overridden by a class (some libraries return arrays or custom objects from ==, which breaks if conditions). It also signals your intent: you are asking about the "no value" marker, not about equality.
The same reasoning applies to other singletons, but you rarely need it. For booleans, write if flag: rather than if flag is True:. The shorter form also accepts truthy values you may want to allow, and linters flag the longer one.
`is None` versus truthiness
Truthiness lumps None, 0, '', [], and {} together as falsy. When "missing" and "empty or zero" mean different things, test for None explicitly.
count = 0
if not count:
print('zero or missing')
if count is None:
print('missing')
else:
print('a number was provided')Here 0 is a legitimate value. The truthiness test cannot tell it apart from None, while is None can.
This matters most for default arguments. A common pattern uses None as a placeholder and builds a fresh object inside the function.
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag('a')) # ['a']
print(add_tag('b')) # ['b'] (a new list each call)
existing = []
add_tag('c', existing)
print(existing) # ['c'] (the caller's empty list was used)If the function used if not tags: instead, a caller who passed their own empty list would have it silently replaced by a new one, and existing would stay empty. The is None test only replaces the argument when nothing was passed.
Using these tests in an `if`/`elif`/`else` chain
The three operators combine naturally with the chain structure you already know. Consider a dictionary where a key can be absent, present with no value, or present with a value.
user = {'name': 'Ana', 'email': None}
if 'email' not in user:
print('no email field')
elif user['email'] is None:
print('email field is empty')
elif '@' not in user['email']:
print('email looks invalid')
else:
print('email ok:', user['email'])Each test depends on the previous ones having failed. The second branch is only safe because the first confirmed the key exists. The third branch is only safe because the second confirmed the value is not None, so '@' not in user['email'] never runs in against None. Evaluating '@' in None would raise TypeError: argument of type 'NoneType' is not iterable.
You can get the same safety inside one condition with short-circuiting, which the previous chapter covered.
email = None
if email is not None and '@' in email:
print('has an @')
else:
print('missing or no @')The order matters. email is not None runs first, and when it is False, and stops before the in test.
Common mistakes
- Using
orwith a list of values.if color == 'red' or 'green':is always truthy, because the non-empty string'green'is a complete condition on its own. Writeif color in ('red', 'green'):. - Using
isto compare numbers or strings. It may work in a quick test and fail later. Use==. - Using
==to compare withNone. It usually works, butis Noneis correct in every case. - Expecting
inon a dict to search values. It searches keys. Use.values()for values. - Forgetting that
inon a string is a substring test.'admin' in 'administrator'isTrue. If you need an exact match, use==or a set of allowed strings. - Testing
not x is None. Python parses this asnot (x is None), which is correct, butx is not Noneis clearer.
Exercises
Exercise
What does this print, and why? data = {'a': 1, 'b': 2} print(1 in data) print('a' in data) print(1 in data.values())
Show answer
It prints False, True, True. The in operator on a dict tests keys, so 1 in data is False (1 is a value) and 'a' in data is True. Calling .values() makes in check the values, so the last line is True.
Exercise
A function has the signature def pad(text, width=None). Callers may pass width=0, which should mean "no padding". Why should the function test if width is None: for the default, and what would go wrong with if not width:?
Show answer
0 is a valid value that is falsy, so if not width: would treat width=0 the same as "not provided" and apply the default instead of the caller's request. if width is None: only triggers when nothing was passed, so 0 is kept.
Exercise
Rewrite if status == 'new' or 'open' or 'pending': so it tests whether status is one of the three strings. Then explain why the original is always true.
Show answer
Write if status in ('new', 'open', 'pending'):. The original parses as (status == 'new') or 'open' or 'pending'. The string 'open' is non-empty and therefore truthy, so the whole condition is true no matter what status is.