Python Set difference_update()

Python Set difference_update() method

Python Set difference_update() method updates the set with the difference of the other set from the set.

difference_update() and difference() methods does the same, except for the difference_update() updates the set while the difference() returns the resulting set.

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

Syntax of Set difference_update()

The syntax of difference_update() method is

set.difference_update(s)

Parameters

Set difference_update() method takes one parameter.

ParameterDescription
sRequired
A Python Set object.

Return value

difference_update() method returns None.

Usage

For example, consider the following statement.

set_1.difference_update(set_2)

The updated set_1 now contains elements of original set_1 that are not present in set_2.

Please note that the difference_update() method updates the original set.

Examples

1. Updating set with the difference of the sets in Python

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

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_1.difference_update(set_2)

print(set_1)
Run Code Copy

Output

{'a', 'b'}

Summary

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

Code copied to clipboard successfully 👍