Sub topic 12
Membership tests with in and not in
This chapter covers the in and not in operators. It assumes you know Python's core built-in types (str, list, tuple, dict, set), how to run a script or the REPL, and how comparison with == works. Identity versus equality was covered in an earlier chapter, and it matters here because membership uses both.
What a membership test does
x in container evaluates to True if x is found in container, and False otherwise. x not in container is the exact opposite. Both always return a bool.
print(3 in [1, 2, 3])
print(4 in [1, 2, 3])
print(4 not in [1, 2, 3])
print("py" in "python")
print("a" in {"a": 1})The meaning of "found" depends on the container type:
| Container | What `in` checks | Typical cost |
|---|---|---|
| `list`, `tuple` | Each item, from the left | O(n) |
| `str` | Whether the left side is a substring | O(n) |
| `dict` | Keys only, not values | O(1) average |
| `set`, `frozenset` | Elements | O(1) average |
| `range` | Arithmetic on the bounds, not a scan | O(1) for ints |
| `bytes`, `bytearray` | An int 0 to 255, or a sub-sequence of bytes | O(n) |
How Python evaluates `in`
For x in y, Python tries these steps in order:
- If
type(y)defines__contains__, cally.__contains__(x)and convert the result to abool. - Otherwise, if
yis iterable, walk it withiter(y)and returnTrueat the first itemitemwhereitem is x or item == x. - Otherwise, if
ydefines__getitem__with integer indexes starting at 0, try each index untilIndexError. - Otherwise, raise
TypeError.
The "identity first, then equality" check in step 2 is the same shortcut that built-in containers use. It explains a well-known oddity with nan:
nan = float("nan")
items = [nan]
print(nan == nan)
print(nan in items)
print(float("nan") in items)The first line prints False, because nan is never equal to anything. The second prints True, because the list scan finds the very same object and the identity check succeeds before == is tried. The third prints False, because it is a different nan object.
Strings: substrings, not items
On strings, in tests for a substring of any length, not for a single character.
print("th" in "python")
print("" in "python")
print("PY" in "python")This prints True, True, False. Two details matter:
- The empty string is a substring of every string, so
"" in sis alwaysTrue. - The test is case-sensitive. Normalize first with
.lower()or.casefold()if you need a case-insensitive check.
The left operand must also be a string. 1 in "123" raises TypeError: 'in <string>' requires string as left operand, not int.
Dictionaries check keys
in on a dictionary looks only at keys. To test values, ask for them explicitly.
prices = {"apple": 1.5, "pear": 2.0}
print("apple" in prices)
print(1.5 in prices)
print(1.5 in prices.values())
print(("pear", 2.0) in prices.items())This prints True, False, True, True. Key lookup uses the hash table, so it is fast. prices.values() has to be scanned linearly. The .items() view supports in with a (key, value) pair.
Because in on a dict never raises KeyError, it is the usual guard before reading a key you are not sure exists. For a read-with-default, prices.get("kiwi", 0) is often simpler.
Sets and speed
Checking membership in a list scans it. Checking in a set hashes the value and jumps to the right bucket. For repeated lookups against a large collection, convert it once.
import time
data = list(range(100_000))
lookup = set(data)
targets = range(99_000, 100_000)
start = time.perf_counter()
hits_list = sum(1 for t in targets if t in data)
list_time = time.perf_counter() - start
start = time.perf_counter()
hits_set = sum(1 for t in targets if t in lookup)
set_time = time.perf_counter() - start
print(hits_list, hits_set)
print(list_time > set_time)Both counts are 1000. The last line prints True on any ordinary machine, because each list lookup walks up to 100,000 items. Building the set costs O(n) once, so it pays off only when you test membership many times.
Tuples and lists compare by equality
On a list or tuple, in uses == after the identity shortcut. That means equal but distinct objects are found.
points = [(0, 0), (1, 2)]
print((1, 2) in points)
matrix = [[1, 2], [3, 4]]
print([3, 4] in matrix)
print(3 in matrix)This prints True, True, False. The search is not recursive. 3 is inside [3, 4], but matrix contains lists, not integers, so 3 in matrix is False.
Numeric equality also crosses types, because 1 == 1.0 == True:
print(1.0 in [1, 2])
print(True in [1, 2])
print(2 in {2.0})All three print True. Watch for this when a list mixes booleans and integers.
`not in` versus `not (x in y)`
x not in y is a single operator. It gives the same answer as not (x in y), but it is the preferred form and reads more naturally. Style guides discourage not x in y. Precedence makes it still correct, because in binds tighter than not, but it is easy to misread.
banned = {"root", "admin"}
user = "guest"
if user not in banned:
print("allowed")Membership as a comparison operator
in and not in have the same precedence as <, ==, is and the other comparison operators, so they chain. This is legal but seldom clear.
print(1 in [1, 2] in [[1, 2], [3]])That expands to (1 in [1, 2]) and ([1, 2] in [[1, 2], [3]]), which is True. Avoid this in real code. The more common precedence question is mixing in with and/or:
role = "editor"
print(role == "admin" or "editor")
print(role in ("admin", "editor"))The first line prints editor, because or returns the non-empty string "editor" regardless of role. It reads like "role is admin or editor" but it is not that. The second line does what you intended and prints True. Using in with a tuple or set of choices is the correct way to compare one value against several.
Making your own class support `in`
Define __contains__ to control the behavior. If you define only __iter__, in still works through the scan in step 2.
class Interval:
def __init__(self, low, high):
self.low = low
self.high = high
def __contains__(self, value):
return self.low <= value <= self.high
temperature = Interval(10, 30)
print(20 in temperature)
print(45 in temperature)
print(45 not in temperature)This prints True, False, True. The class does not need to be iterable. not in simply negates whatever __contains__ returns.
Common errors
- Using
inon a number:3 in 123raisesTypeError: argument of type 'int' is not iterable. - Expecting
inon a dict to search values. - Passing an unhashable item to a set or dict, such as a list.
- Forgetting that
"" in sis alwaysTrue. - Writing
x == "a" or "b"instead ofx in ("a", "b"). - Doing repeated lookups on a long list when a set would do.
Exercise
Predict the output of each line, then explain the third. d = {"a": 1, "b": 2} print("b" in d) print(2 in d) print(("b", 2) in d.items()) print("" in "abc")
Show answer
The lines print True, False, True, True. "b" is a key, so the first test is True. in on a dict checks keys only, and 2 is a value, so the second is False. The third is True because d.items() yields (key, value) pairs and ("b", 2) is one of them. The empty string is a substring of every string, so the last is True.
Exercise
This function is meant to return True when color is red, green or blue, but it returns True for any color. Fix it and say why it was wrong.
def is_primary(color):
return color == "red" or "green" or "blue"
Show answer
Use return color in {"red", "green", "blue"}. The original parses as (color == "red") or "green" or "blue". When the first comparison is False, or moves on and returns "green", a non-empty string that is truthy, so the function never returns a falsy value for any input.