Python

issuperset method in set

Click for All Topics

issuperset method in set - Python

  • This method is used to check whether a set is a superset of another set or we can say it contains all elements of another set.
  • Set A is called a superset of Set B if all elements of the set B are present in Set A.
  • It returns true if set A is a superset of B otherwise it returns false.
  • This method takes exactly one argument.
  • We can pass any iterable or collections data type element as an argument e.g. list, tuple, dictionary, set, etc.

 

Syntax –

set_name.issubset(iterable)

 

Parameter –

  • iterable → any iterable or collection data type element e.g. list, tuple, set, dictionary, etc.
  • Return value → bool(True or False).

 

Example 1-

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

print("Set 1:",set1)
print("Set 2:",set2)
print("set2 is superset of set1:",set1.issuperset(set2))

# Output - 
# Set 1: {1, 2, 3}
# Set 2: {1, 2, 3, 4, 5}
# set2 is superset of set1: True
				
			
  • In the above example, first we create two sets set1 and set2 with some elements.
  • After creating both sets print both sets on the output screen.
  • Finally, we check whether set2 is a superset set1 using .issuperset() method and print the output.

 

Example 2-

				
					s={'a','b','c','d','e','f','g','h'}
s1={'a','c','e','h'}

print("First Set:",s)
print("Second set:",s1)
print("s is a superset of s1:",s.issuperset(s1))

# Output -
# First Set: {'f', 'g', 'd', 'e', 'c', 'h', 'b', 'a'}
# Second set: {'h', 'e', 'a', 'c'}
# s is a superset of s1: True
				
			

The .issuperset() method with another type of collection –

Example 3-

				
					set1 = [10, 20, 30]
set2 = {10, 20, 30, 40, 50}

print("Set 1:",set1)
print("Set 2:",set2)

print("set2 is superset of set1:",set1.issuperset(set2))

# Output -
# Set 1: [10, 20, 30]
# Set 2: {50, 20, 40, 10, 30}
# set2 is superset of set1: True
				
			

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

Example 4-

				
					def is_superset(set1, set2):
    # Check if every element in set2 is also in set1
    for element in set2:
        if element not in set1:
            return False
    return True

# Example usage:
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}

result = is_superset(set1, set2)
print("set1 is superset of set2:",result)

# Output -
# set1 is superset of set2: True