Python Set – difference()

Python Set difference() method

Python Set difference() method is used to find the set of elements that are present in this set and not present in the other set.

In this tutorial, we will learn the syntax and usage of difference() method.

Syntax – difference()

The syntax of difference() method is

set_3 = set_1.difference(set_2)
Run

set_1 and set_2 are unchanged. set_3 contains elements of set_1 that are not present in set_2.

Example 1: Set Difference

In this example, we shall initialize two sets, set_1 and set_2 with some elements. Then we shall apply difference() method on set_1 and pass set_2 as argument to difference method.

Following is a simple demonstration of how the output would be.

{'a', 'b', 'c', 'd'} - {'c', 'd', 'e', 'f'} = {'a', 'b'}
Run

Elements c and d are present in set_2. Hence the difference results in set_1 without these common elements of set_1 and set_2.

Python Program

#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'c', 'd', 'e', 'f'}

#find difference
set_3 = set_1.difference(set_2)

print(set_3)
Run

Output

{'a', 'b'}

Example 2: Python Set difference() method chaining

You can chain difference() method with multiple sets.

The statement

set_4 = set_1.difference(set_2).difference(set_3)
Run

denotes that

set_4 = set_1 - set_2 - set_3
Run

Following is a python program to demonstrate the chaining of set difference() method.

Python Program

#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'c', 'd', 'e', 'f'}
set_3 = {'a'}

#find difference
set_4 = set_1.difference(set_2).difference(set_3)

print(set_4)
Run

Output

{'b'}

Summary

In this tutorial of Python Examples, we learned how to use difference() method of set class in Python, with the help of well detailed example programs.