This guide explains Membership Operators: in and not in through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
in checks membership, while not in checks its absence. Membership means item membership for sequences, substring membership for strings, and key membership for dictionaries.
When You Would Use This
Check whether an entered country code is supported.
Step-by-Step Example
supported_codes = {"US", "CA", "GB"}
selected_code = "GB"
print(selected_code in supported_codes)
print("FR" not in supported_codes)
print("cat" in "concatenate")
How the Example Works
All three expressions evaluate to True. Set membership is typically efficient for large lookup collections, but the choice of container still depends on your application.
Example Output
True
True
True
Try It Yourself
Create a list of allowed user roles and check both an allowed and a missing role.
Common Beginner Mistakes
- Expecting
inon a dictionary to check values rather than keys. - Forgetting that string substring matching is case-sensitive.
- Testing a numeric item against a string without converting types.
Key Takeaways
inchecks membership, whilenot inchecks its absence.- All three expressions evaluate to
True. - Avoid this mistake: Expecting
inon a dictionary to check values rather than keys.