Sub topic 12
Membership tests with in and not in
This chapter assumes you know Python's core types (str, list, tuple, dict, set), how to run a script or the REPL, and how == and is differ. It covers the in and not in operators.
What `in` does
x in container evaluates to True if container holds x, and False otherwise. x not in container is the exact opposite. Both return a bool, so you can use them directly in if statements and in and/or expressions.
print(3 in [1, 2, 3])
print("py" in "python")
print("a" in {"a": 1})
print(4 not in (1, 2, 3))This prints True, True, True, True.
What "contains" means for each type
The meaning of "contains" depends on the type on the right.
| Container | `x in container` is true when | Typical cost |
|---|---|---|
| `list`, `tuple` | some element equals `x` | linear, checks items one by one |
| `str` | `x` is a substring | linear in string length |
| `dict` | `x` is a key | constant on average |
| `set`, `frozenset` | `x` is an element | constant on average |
| `range` | `x` is a member of the sequence | constant for ints |
Three details cause most mistakes:
- For a dictionary,
inchecks keys only. Usein d.values()to check values. - For a string, the left side must also be a string.
1 in "123"raisesTypeError. - The empty string is a substring of every string, so
"" in "abc"isTrue.
prices = {"apple": 3, "pear": 5}
print("apple" in prices)
print(3 in prices)
print(3 in prices.values())
print("" in "abc")How Python evaluates it
For lists and tuples, Python compares each item with x. It first checks identity and then equality, so x is item or x == item. This is why float("nan") in [nan] can be True when the same nan object is stored, even though nan == nan is False.
For sets and dicts, Python hashes x and looks in a hash table. This means x must be hashable. Testing [1] in {1, 2} raises TypeError: unhashable type: 'list'.
A class can support in by defining __contains__. If it does not, Python falls back to iterating the object, or to __getitem__ with integer indexes.
Choosing a container
If you test membership many times against the same collection, convert a list to a set once. The check then no longer slows down as the collection grows.
allowed = {"admin", "editor", "viewer"}
role = "editor"
if role in allowed:
print("access granted")Use in for membership and == for comparing one value with another. Do not use is for either. x in (None,) works, but x is None is the correct test for None.
Common errors
- Writing
if x == 1 or 2:. Theor 2part is always truthy. Writeif x in (1, 2):. - Writing
not x in items. It works, because Python reads it asnot (x in items), butx not in itemsis clearer. - Testing
inon a generator. The test consumes items from it, so a later test sees fewer items.
Exercise
What do "b" in "abc", "b" in ["abc"], and "b" in {"b": 0} print?
Show answer
True, False, True. In a string, in tests for a substring. In a list, it tests for an element equal to "b", and the only element is "abc". In a dict, it tests keys, and "b" is a key.
Exercise
Rewrite if color == "red" or "green" or "blue": so that it correctly tests whether color is one of the three names.
Show answer
if color in ("red", "green", "blue"):. The original is always true, because the non-empty string "green" is truthy. A set literal {"red", "green", "blue"} also works.