How to Check if a Set is a Subset in Python
Check whether one set contains all elements of another set using the issubset method.
Python code
15 linesdef is_subset(allowed_set, check_set):
"""
Check if check_set is a subset of allowed_set.
Returns True if all elements of check_set are in allowed_set, otherwise False.
"""
return check_set.issubset(allowed_set)
if __name__ == "__main__":
# Example usage
allowed = {1, 2, 3, 4, 5}
valid = {2, 3}
invalid = {3, 6, 7}
print(f"Valid subset: {is_subset(allowed, valid)}")
print(f"Invalid subset: {is_subset(allowed, invalid)}")
Output
Valid subset: True
Invalid subset: False
How it works
The check_set.issubset(allowed_set) method returns True if every element of check_set is present in allowed_set. This is equivalent to the <= operator for sets. The method handles empty sets gracefully, returning True because an empty set is a subset of any set. Using issubset is efficient and reads clearly in code.
Common mistakes
- Using `in` to check each element individually instead of the built-in method
- Confusing `issubset` with `issuperset`, which checks the opposite direction
- Forgetting that sets require hashable elements, which may cause errors
Variations
- Use the `<=` operator: `check_set <= allowed_set`
- Use `allowed_set.issuperset(check_set)` for the same check reversed
Real-world use cases
- Validating user permissions: checking if a user's role set is a subset of allowed roles for an action.
- Filtering configuration flags: verifying that all requested feature flags are within the supported set.
- Data validation: ensuring a set of input categories is a subset of known valid categories before processing.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.