Python

issubset method in set

Click for All Topics

issubset method in set - Python

  • This method is used to check whether a set is a part or subset of another set or not.
  • set B is called a subset of set A if all elements of set B are present in set A.
  • If set B is a subset of A then this method returns true otherwise it returns false.
  • This method takes exactly one argument.
  • We can pass any iterable or collection as an argument e.g. list, tuple, dictionary, set, etc.
  • We can also use the <= operator instead of the .issubset() method.

Syntax –

set_name.issubset(iterable)

Parameter –

  • iterable → any iterable or collection data type element.
  • Return value → bool(True or False).

Example 1-

				
					A={1,2,3,4,5,6,7,8,9}
B={1,3,5,7,9}
print("Set A:",A)
print("Set B:",B)
print("Set B is a subset of Set A:",B.issubset(A))

# Output -
# Set A: {1, 2, 3, 4, 5, 6, 7, 8, 9}
# Set B: {1, 3, 5, 7, 9}
# Set B is a subset of Set A: True
				
			
  • In the above example, first we create two sets A and B with some elements.
  • After creating both sets print both sets on the output screen.
  • Finally, we check whether set B is a subset of set A or not and print the output on the output screen.

Example 2-

				
					s={'e','d','S','l','a','s','h'}
s1={'a','b','c','d','e','f','g','h','s'}
print("Set 1:",s)
print("Set 2:",s1)
print("Set s1 is a subset of set s:",s1.issubset(s))

# Output -
# Set 1: {'e', 'l', 'h', 'a', 's', 'd', 'S'}
# Set 2: {'b', 'e', 'f', 'g', 'h', 'a', 's', 'd', 'c'}
# Set s1 is not a subset of set s: False
				
			

issubset() method with the list –

Example 3-

				
					l=['Anurag','Nitin','Niketan']
s={'Anurag'}
print("List :",l)
print("Set :",s)
print("Set s is a subset of list l:",s.issubset(l))

# Output -
# List : ['Anurag', 'Nitin', 'Niketan']
# Set : {'Anurag'}
# Set s is a subset of list l: True
				
			

how to check whether a set is a subset of another set without using any built-in method –

Example 4-

				
					set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

print("set1 :",set1)
print("set2 :",set2)

is_subset = set1 <= set2
print("set1 is subset of set2:",is_subset)  

# Output -
# set1 : {1, 2, 3}
# set2 : {1, 2, 3, 4, 5}
# set1 is subset of set2: True