Computer Science · Ch 5 — Getting Started with Python
Membership Operators
Membership Operators
Membership operators are used to check whether a value is a member of a given sequence or not. Instead of comparing two values, they search: "does this item occur anywhere inside that collection?" The answer is always a Boolean — True or False.
Python has two membership operators: in and not in.
The in operator
Returns True if the variable or value is found in the specified sequence, and False otherwise.
>>> a = [1, 2, 3]
>>> 2 in a
True
>>> '1' in a
False
Note the second result carefully: the list contains the integer 1, not the string '1'. Membership testing respects data types — a string '1' is a different value from the number 1, so it is not found in the list.
The not in operator
Returns True if the variable or value is not found in the specified sequence, and False otherwise — the exact opposite of in.
>>> a = [1, 2, 3]
>>> 10 not in a
True
>>> 1 not in a
False
10 does not occur in the list, so 10 not in a is True; 1 does occur, so 1 not in a is False.
Quick reference
| Operator | Returns True when… |
|---|---|
in | the value is found in the sequence |
not in | the value is not found in the sequence |
| Operator | Description | Example (Try in Lab) |
|---|---|---|
| in | Returns True if the variable/value is found in the specified sequence and False otherwise | >>> a = [1,2,3] >>> 2 in a True >>> '1' in a False |