Python Set difference()

Python Set difference() method

Python Set difference() method returns the set of elements that are present in this set and not present in the other set. Here this set is the set on which we are calling the difference() method, and the other set is the set that we passed as argument to the the difference() method.

In this tutorial, you will learn the syntax and usage of Set difference() method, with examples.

Syntax of Set difference()

The syntax of difference() method is

set.difference(s)

Parameters

Set difference() method takes one parameter.

ParameterDescription
sRequired
A Python Set object.
Python Set difference() method parameters table

Return value

difference() method returns a Set object.

Usage

For example, consider the following statement.

set_3 = set_1.difference(set_2)

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

Examples

1. Finding difference between two given Sets in Python

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'}

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 Code Copy

Output

{'a', 'b'}

2. Chaining of Set difference() method

You can chain difference() method with multiple sets.

The statement

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

denotes that

set_4 = set_1 - set_2 - set_3

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 Code Copy

Output

{'b'}

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍