Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
data structures
difference()
community creator

How difference() works in Python

Hassan Ahmed

The difference() method in Python returns a set, which contains the set difference of two sets.

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

If we’re finding set difference (A-B), the new set would contain elements in Set A and omit any element that exists 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.symmetric_difference(set2)

Parameters and return value

This method requires only one set to be passed as a parameter. The elements of this set are checked, and not included in the returned set.

Code

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

z = x.difference(y)
print(z)

RELATED TAGS

python
data structures
difference()
community creator
RELATED COURSES

View all Courses

Keep Exploring