Python Set Membership with in and not in
Core idea
value in members returns a Boolean indicating whether the value is present. not in tests absence. A list can also answer membership questions, but a set stores only distinct members and normally uses hashing for lookup. For repeated lookups among hashable values, building a set once can be useful; conversion has a cost and speed is not guaranteed for every input.
allowed = {"A2", "B4"}print("A2" in allowed)print("C1" not in allowed)Both tests succeed, for presence and absence respectively.
Check several requests
allowed = {3, 7}for number in [7, 4, 3]: print(number in allowed)The set is constructed once and reused for all three checks.
Compare list and set membership
codes = [4, 4, 9]print(4 in codes, 4 in set(codes))print(len(codes), len(set(codes)))Both recognize 4, but only the list retains repeated occurrences.
Common mistake
Set membership checks whole elements, not substrings. For example, "ab" in {"abc"} is False.
Practice
Build a set of accepted room labels and print membership for one known and one unknown label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set membership
Check your understanding of membership.
What is printed?
print(2 in {2, 5})What is printed?
print(0 not in {2, 5})What is printed?
print("a" in {"ab"})Why might a set help with many membership checks?