Topic 39 of 64
in, not in
Overview
'in' and 'not in' test whether a value is a member of a sequence or collection. They work on strings, lists, tuples, sets, and dicts (key check). Set membership is O(1) while list membership is O(n).
Syntax
python
# List membership — O(n)
3 in [1, 2, 3, 4] # True
5 not in [1, 2, 3] # True
# String membership
"ell" in "hello" # True (substring check)
"xyz" not in "hello" # True
# Set membership — O(1)
5 in {1, 3, 5, 7} # True
# Dict membership (checks keys)
"name" in {"name": "Alice"} # True
"Alice" in {"name": "Alice"} # False (checks keys)Common Pitfalls
- Using 'in' on a list is O(n) — for repeated lookups on large collections, convert to a set first for O(1) performance.
- 'in' on a dict checks keys only — use 'in dict.values()' to check values (still O(n)).
- Interview tip: 'in' on a string checks for substrings, not character-by-character — 'ab' in 'abc' is True.
Real-World Example
Fast lookup using a set for allowed permissions
example
python
ALLOWED_ROLES = {"admin", "editor", "moderator"}
def check_access(user_role: str, resource: str) -> bool:
if user_role not in ALLOWED_ROLES:
print(f"Role '{user_role}' is not permitted")
return False
print(f"Access granted to {resource}")
return True
check_access("admin", "/dashboard") # Access granted
check_access("viewer", "/dashboard") # Role 'viewer' is not permitted