Python Set difference() Method – Tutorial with Examples

Python Set difference() Method

The difference() method in Python Set is used to find the difference between two or more sets. It returns a new set that contains the elements that are present in the original set but not in the specified sets.

Basic Syntax

set1.difference(set2, set3, ...)

Here, set1 is the original set, and set2, set3, etc. are the sets to find the difference with. The difference() method can take any number of sets as arguments.

Return Value

The difference() method returns a new set that contains the elements that are present in the original set but not in the specified sets.

Examples

Example 1: Finding the difference between two sets

In this example, we will find the difference between two sets using the difference() method.

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}

# Finding the difference between two sets
result = set1.difference(set2)

# Printing the result
print(result)

The output of the above code will be:

{1, 3, 5}

As we can see, the difference() method has returned a new set that contains the elements that are present in set1 but not in set2.

Example 2: Finding the difference between more than two sets

In this example, we will find the difference between more than two sets using the difference() method.

# Creating three sets
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}
set3 = {3, 6, 9}

# Finding the difference between three sets
result = set1.difference(set2, set3)

# Printing the result
print(result)

The output of the above code will be:

{1, 5}

As we can see, the difference() method has returned a new set that contains the elements that are present in set1 but not in set2 or set3.

Example 3: Finding the difference between sets with different data types

In this example, we will find the difference between sets that have different data types.

# Creating two sets with different data types
set1 = {1, 2, 3, 4, 5}
set2 = {'a', 'b', 'c'}

# Finding the difference between two sets
result = set1.difference(set2)

# Printing the result
print(result)

The output of the above code will be:

{1, 2, 3, 4, 5}

As we can see, the difference() method has returned a new set that contains all the elements of set1 because set2 is of a different data type.

Use Cases

The difference() method can be used in a variety of scenarios, such as:

  • Removing common elements from multiple sets.
  • Finding the unique elements in a set that are not present in another set.
  • Filtering out unwanted data from a dataset based on specific criteria.

Leave a Reply

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