Python Set – difference_update()

Python Set difference_update() method

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

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

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

Syntax – difference_update()

The syntax of difference_update() method is

set_1.difference_update(set_2)
Run

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

Example 1: Python Set difference_update()

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

print(set_1)
Run

Output

{'a', 'b'}

Example 2: Python Set difference_update() method chaining

Since difference_update() method does not return the resulting set, but just updates the original set, chaining cannot be done with difference_update() method.

The statement

set_1.difference_update(set_2).difference_update(set_3)
Run

returns AttributeError.

AttributeError: 'NoneType' object has no attribute 'difference_update'
Run

Following is a python program to demonstrate the error.

Python Program

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

#find difference
set_1.difference_update(set_2).difference_update(set_3)

print(set_1)
Run

Output

AttributeError  Traceback (most recent call last)
<ipython-input-2-f1cfc9906cbb> in <module>
      5 
      6 #find difference
----> 7 set_1.difference_update(set_2).difference_update(set_3)
      8 
      9 print(set_1)

AttributeError: 'NoneType' object has no attribute 'difference_update'

Summary

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