Python Set issubset:

The issubset() method checks whether elements from one set are present in another and returns True or False accordingly. For example, Set A is subset of B if and only if all the elements of Set A are present in Set B. In other words, the issubset method works in the opposite way of the issubset method.

Method signature

The signature for the issubset() method is as shown below. Here, A and B are set. In this case, the method returns True if and only if all the elements of set A are present in Set B. Otherwise, it returns False.

A.issubset(B)

Method parameters and return type

  • The issubset() method takes one parameter
  • However, it returns boolean value True or False depending on the data set.

Python Set issubset Examples:

Example 1:

In this example, let us take a set A and a set B with a set of numbers.

#Initializing the Set
A = {14,15,16,19,29,39}
B={19,29,39}
# Checking if A is subset of B
result=A.issubset(B)
print("Is A subset of B",result)
# Checking if B is subset of A
result=B.issubset(A)
print("Is B subset of A",result)


Output

Is A subset of B False
Is B subset of A True


Example 2:

Let us consider a set containing cities in this example. Python is case sensitive, if the city name doesn’t match exactly, this method will return False.

#Initializing the Set
A={"Delhi", "Bhopal", "Chennai", "Jodhpur"}
B={"Delhi", "Chennai"}
C={"delhi", "Bhopal"}
# Checking if B is subset of A and printing
print("Is B subset of A",B.issubset(A))
# Checking if C is subset of A and printing
print("Is C subset of A",C.issubset(A))


Output

Is B subset of A True
Is C subset of A False


Example 3:

In this example, let us demonstrate the issubset method on a mixed set. Here, we are taking a set B representing an employee’s record with his name and id. Thereafter, we have to check the presence of that Employee’s record in a set referred as A that contains data of all employees.

#Initializing the Set
A={"Ram", 15,"Sam", 25, "Harry",3,"John",8}
B={"Sam",25}
# Using issubset method and printing the result
print("Is B subset of A",B.issubset(A)) 


Output

Is B subset of A True


Conclusion

The issubset() method returns boolean value to indicate if one set is subset of another or not.

References

Happy Learning 🙂

Leave A Comment