Python Set issubset() Method – Tutorial with Examples

Python Set issubset() Method

A set is an unordered collection of unique elements. Python provides several built-in methods for manipulating sets, including the issubset() method. The issubset() method returns a Boolean value indicating whether the set is a subset of another set.

Syntax

set.issubset(set)

The issubset() method takes one argument as a set and returns True if the set is a subset of the given set. Otherwise, it returns False.

Return Value

  • If the set is a subset of the given set, it returns True.
  • If the set is not a subset of the given set, it returns False.

Examples

Example 1: Using issubset() method with two sets

Let’s create two sets and check if the first set is a subset of the second set using the issubset() method:

# Create two sets
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Check if set1 is a subset of set2
result = set1.issubset(set2)

# Print the result
print(result)

Output:

True

In the above example, we created two sets (set1 and set2) and checked if set1 is a subset of set2 using the issubset() method. Since all the elements of set1 are present in set2, the method returns True.

Example 2: Using issubset() method with a superset

Let’s create a set and check if it is a subset of a superset using the issubset() method:

# Create a set and a superset
set1 = {1, 2, 3}
superset = {1, 2, 3, 4, 5}

# Check if set1 is a subset of superset
result = set1.issubset(superset)

# Print the result
print(result)

Output:

True

In the above example, we created a set (set1) and a superset (superset) and checked if set1 is a subset of the superset using the issubset() method. Since all the elements of set1 are present in superset, the method returns True.

Example 3: Using issubset() method with a non-subset

Let’s create two sets and check if the first set is a subset of the second set using the issubset() method:

# Create two sets
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3}

# Check if set1 is a subset of set2
result = set1.issubset(set2)

# Print the result
print(result)

Output:

False

In the above example, we created two sets (set1 and set2) and checked if set1 is a subset of set2 using the issubset() method. Since set1 contains an element (4) that is not present in set2, the method returns False.

Use Cases

The issubset() method is particularly useful when dealing with large sets, as it allows you to quickly check whether one set is a subset of another set. This can be useful in a variety of applications, such as:

  • Checking if a specific set of items is present in a larger dataset
  • Determining if a user has access to a particular set of resources or permissions
  • Comparing two different sets of data to see if they share any common elements

Overall, the issubset() method is a powerful tool for working with sets in Python, and can be used in a wide range of applications.

Leave a Reply

Your email address will not be published. Required fields are marked *