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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 17 views 0 copies

Python code

15 lines
Python 3.9+
def 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

stdout
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

  1. Use the `<=` operator: `check_set <= allowed_set`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.