Related Tags

python
communitycreator

# How to determine if a set is a subset of another set in Python

Sarah Tanveer

Sets are unordered data structures that do not contain duplicates. In this shot, we will discuss how to determine if a set is a subset of another set.

### What is a subset?

If all the values of a set, A, are also contained in a larger set, B, then A is a subset of B.

Set A is a subset of B

### 1. How to use issubset()

The built-in function issubset() can be used to determine if a set is a subset of another set.

setA.issubset(setB)


The issubset() function takes one argument: the larger set. Here, we are checking if setA is a subset of setB.

The function will return True if setA is a subset of setB and False if it is not.

setA = {1, 2, 3, 4, 5}
setB = {1, 2, 3}
setC = {1, 2, 3, 6, 7}
print("setA: ", setA)
print("setB: ", setB)
print("setC: ", setC)

print("Is setB a subset of setA?: ", setB.issubset(setA))
print("Is setA a subset of setB?: ", setA.issubset(setB))
print("Is setC a subset of setA?: ", setC.issubset(setA))

### 2. How to use intersection()

The built-in intersection() function returns a set that contains the elements that the two sets share.

set.intersection(set1)


If the set that intersection returns is equal to the smaller set, the smaller set is a subset of the larger set.

setA = {1, 2, 3, 4, 5}
setB = {1, 2, 3}
setC = {1, 2, 3, 6, 7}
print("setA: ", setA)
print("setB: ", setB)
print("setC: ", setC)

print("Is setB a subset of setA?: ", setA.intersection(setB) == setB)
print("Is setA a subset of setB?: ", setA.intersection(setB) == setA)
print("Is setC a subset of setA?: ", setA.intersection(setC) == setC)



### 3. How to use a for loop

We can use a simple for loop to traverse through the potential subset, say, setB.

If any element of setB is not in the other set, setA, then setB is not a subset of setA. Otherwise, setB is a subset of setA.

setA = {1, 2, 3, 4, 5}
setB = {1, 2, 3}

print("setA: ", setA)
print("setB: ", setB)

subSet = True

for i in setB:
if i not in setA:
subSet = False

if subSet == False:
print("SetB is not a subset of SetA")
else:
print("SetB is a subset of SetA")

for i in setA:
if i not in setB:
subSet = False

if subSet == False:
print("SetA is not a subset of SetB")
else:
print("SetA is a subset of SetB")


RELATED TAGS

python
communitycreator

CONTRIBUTOR

Sarah Tanveer
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 