# 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 inrange(10))
print(f"5 in gen: {5 in gen}")
print(f"Remaining: {list(gen)}") # only elements after 5
Output
Click "Run" to execute your code
'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.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?