Skip to content

How to Check If a Set Is a Subset of Another Set in Python

Learn how to verify if one Python set contains all elements of another using issubset() or the <= operator, including proper subset checks.

In Python, a set is considered a subset of another if every element in the first set is also contained within the second set. Checking for this relationship is fundamental when validating data permissions, filtering categories, or performing mathematical set operations.

This guide explains how to check for subset relationships using the readable .issubset() method and the concise <= operator, while highlighting the distinction between standard subsets and proper (strict) subsets.

Understanding the Subset Relationship

Set A is a subset of Set B if all elements of A are present in B.

  • A = {1, 2}
  • B = {1, 2, 3, 4}
  • Result: A ⊆ B is True.

If A contains even one element not found in B, it is not a subset.

Method 1: Using the issubset() Method

The built-in set.issubset(other) method allows you to check if the set is a subset of other. This method is readable and flexible.

skills_junior = {"Python", "Data Analysis"}
skills_senior = {"Python", "Data Analysis", "Machine Learning", "SQL"}

is_subset = skills_junior.issubset(skills_senior)

print(f"Is subset? {is_subset}")

Output:

Is subset? True

Handling Non-Subset Cases

If the first set has extra elements, the method returns False.

skills_cloud = {"Python", "AWS"} # AWS is not in senior skills
skills_senior = {"Python", "Data Analysis", "Machine Learning", "SQL"}

print(skills_cloud.issubset(skills_senior))

Output:

False

Method 2: Using the <= Operator

Python allows you to use mathematical comparison operators for sets. The <= operator checks if the left operand is a subset of the right operand.

set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}

if set_a <= set_b:
    print("Set A is a subset of Set B")
else:
    print("Set A is NOT a subset of Set B")

Output:

Set A is a subset of Set B

Checking for Proper Subsets (Strict)

A proper subset (or strict subset) means Set A is inside Set B, but A is not equal to B (i.e., B has at least one extra element).

  • Use <= for "Subset or Equal".
  • Use < for "Proper Subset".
set_x = {1, 2, 3}
set_y = {1, 2, 3} # Identical to set_x

print(f"Is subset (<=): {set_x <= set_y}")

print(f"Is proper subset (<): {set_x < set_y}")

Output:

Is subset (<=): True
Is proper subset (<): False

Conclusion

To check subset relationships in Python:

  1. Use set_a.issubset(set_b) for readability and when comparing against non-set iterables (like lists).
  2. Use set_a <= set_b for concise, mathematical syntax when comparing two sets.
  3. Use set_a < set_b if you need to ensure set_a is smaller than and not equal to set_b.
Navigation