not in
Absence, spelled the way you say it: `if key not in cache:`.
Common call
if key not in cache:
Returns
bool
Replaces
preferred over `not key in cache` — same result, better reading
Watch out
same dict-keys and O(n)-list rules as in
itemitem — The candidate.type: Any · required not in containercontainer — Where to look.type: iterable · required
→ bool
Demo
Live evaluation
Try:
Inputs
itemAnyto find
containerlistcomma-separated items
Output
'z' not in ['a', 'b', 'c']
True
The exact inverse of in — True for absence. Python treats "not in" as a single operator token, which is why it reads so naturally.
Operands
| Name | Type | Required | Description |
|---|---|---|---|
| item | Any | yes | The candidate. |
| container | iterable | yes | Where to look. |
Return value
bool — True when item is NOT a member of container. Exactly `not (item in container)`, as one readable operator.
Common patterns
Initialize-if-missing
The check-then-create dict pattern.
if key not in groups: groups[key] = [] groups[key].append(item)
Filtering out exclusions
Comprehension with a blocklist.
kept = [x for x in items if x not in BANNED]
Examples
1. Absent element
"z" not in ["a", "b"]
Returns
True2. Missing key
"k" not in {}
Returns
True3. Substring form
"xyz" not in "hello"
Returns
TruePitfalls
1. `not x in y` reads wrong
Identical semantics, but the split spelling invites misreading — and linters flag it.
Awkward
if not key in d:
works; flagged by style checkers
Fix
if key not in d:
idiomatic
When to use
Use it
- Absence checks and guards
- Exclusion filters
Reach for something else
- Absence-then-store on dicts → dict.setdefault covers both steps
- Big-list exclusion sets → convert to set first
Notes
Complexity
same as in: O(1) sets/dicts, O(n) lists
Return
bool
CPython impl
CONTAINS_OP with invert flag — one opcode
Memory
No allocation
Thread-safe
Yes for stable containers
FAQ
Yes — grammatically a single comparison operator, compiled to one opcode. It is not `not` applied afterwards, though the result is identical.
History
1.0
Core operator from the beginning.