in — Intermediate Examples
Membership test operator; also used in for loops to iterate over items
in with different containers
Performance characteristics of membership testing.
python
# Set: O(1) lookup allowed = {"admin", "editor", "viewer"} print(f"'admin' in set: {'admin' in allowed}") # List: O(n) lookup allowed_list = ["admin", "editor", "viewer"] print(f"'admin' in list: {'admin' in allowed_list}") # Range: O(1) in Python 3! big_range = range(1_000_000_000) print(f"999_999 in range: {999_999 in big_range}") # In with generators (consumes elements!) gen = (x for x in range(10)) print(f"5 in gen: {5 in gen}") print(f"Remaining: {list(gen)}") # only elements after 5
Expected Output
True True True True [6, 7, 8, 9]
'in' calls __contains__ if defined. Sets and dicts are O(1), lists are O(n). Python 3's range has O(1) membership testing. Generators are consumed during the search.
not in: the complement
Using 'not in' for negative membership checks.
python
# not in (preferred over 'not x in y') banned = {"spam", "phishing", "malware"} word = "hello" if word not in banned: print(f"'{word}' is allowed") # Filtering with not in all_users = ["alice", "bob", "charlie", "dave"] blocked = {"charlie", "dave"} active = [u for u in all_users if u not in blocked] print(f"Active: {active}") # in with any/all numbers = [2, 4, 6, 8, 10] print(f"Has odd: {any(n % 2 != 0 for n in numbers)}") print(f"All positive: {all(n > 0 for n in numbers)}")
Expected Output
hello' is allowed Active: ['alice', 'bob'] Has odd: False All positive: True
'not in' is a single operator, not 'not' applied to 'in'. It's more readable and slightly faster than 'not (x in y)'.
Want to try these examples interactively?
Open Intermediate Playground