0
0
PythonHow-ToBeginner · 3 min read

How to Check if a Set is Subset in Python

In Python, you can check if a set is a subset of another set using the issubset() method or the subset operator <=. Both return True if all elements of the first set are contained in the second set.
📐

Syntax

There are two common ways to check if a set is a subset of another set in Python:

  • set1.issubset(set2): Returns True if all elements of set1 are in set2.
  • set1 <= set2: The subset operator, returns True if set1 is a subset of set2.
python
set1.issubset(set2)

# or

set1 <= set2
💻

Example

This example shows how to use both issubset() and the <= operator to check if one set is a subset of another.

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

# Using issubset() method
print(set_a.issubset(set_b))  # True

# Using subset operator
print(set_a <= set_b)          # True

# When set_a is not a subset
set_c = {1, 6}
print(set_c.issubset(set_b))  # False
print(set_c <= set_b)          # False
Output
True True False False
⚠️

Common Pitfalls

Some common mistakes when checking subsets include:

  • Using set1 < set2 which checks for a proper subset (set1 is subset but not equal to set2). This returns False if sets are equal.
  • Confusing subset with superset. Use issubset() to check subset, not issuperset().
  • Trying to check subset on non-set types without converting them to sets first.
python
set_x = {1, 2, 3}
set_y = {1, 2, 3}

# Proper subset check (strict subset)
print(set_x < set_y)  # False because sets are equal

# Subset check (allow equal sets)
print(set_x <= set_y) # True

# Wrong: checking subset on lists (will raise error)
# print([1, 2].issubset([1, 2, 3]))  # AttributeError

# Correct: convert lists to sets first
print(set([1, 2]).issubset(set([1, 2, 3])))  # True
Output
False True True
📊

Quick Reference

Summary of subset checks in Python:

OperationDescriptionExampleResult
issubset()Checks if all elements of set1 are in set2set1.issubset(set2)True or False
<= operatorChecks if set1 is subset or equal to set2set1 <= set2True or False
< operatorChecks if set1 is a proper subset of set2 (not equal)set1 < set2True or False
issuperset()Checks if set1 contains all elements of set2set1.issuperset(set2)True or False

Key Takeaways

Use issubset() or <= operator to check if a set is a subset in Python.
The < operator checks for a proper subset, excluding equality.
Always ensure you are working with sets; convert other types like lists to sets first.
Confusing subset and superset methods can lead to wrong results.
Both methods return a boolean indicating subset status.