Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
datastructure
set
difference
communitycreator

How does difference_update() work in Python?

Hassan Ahmed

The difference_update() method in Python is used to find the set difference of two sets and update the set called by the method with that set difference.

To understand the set difference of two sets, consider Set A and Set B.

If we find set difference (A-B), the new set would contain elements that exist in Set A and omit any element that exits in Set B.

To better understand what set difference is, refer to Figure 1.

Figure 1: The set difference of these two sets (A - B) would be the elements that exist in the blue, shaded region.

Syntax

set1.difference_update(set2)

Parameters and return value

The difference_update() method requires only one set to be passed as a parameter, which it will compare with the set called by the method.

It is important to note that this method returns None. Instead, the set that is called by the method will be updated with the set difference.

Code

# Set 1
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
y = {'Dogs', 'Lions', 'Seals', 'Parrots'}

# Set 2
a = {'A', 'B', 'C', 'D', 'E', 'F'}
b = {'B', 'C', 'D', 'F'}

# Method called for Set 1
x.difference_update(y)
print(x)

# Method called for Set 2
a.difference_update(b)
print(a)

RELATED TAGS

python
datastructure
set
difference
communitycreator
RELATED COURSES

View all Courses

Keep Exploring