Python Set difference

Python Set x.difference(y) method returns a new set with the elements of calling set x that are not present in the set y given as argument.

In this tutorial, we will learn the syntax of set.difference() method and go through examples covering different scenarios for the arguments that we pass to difference() method.

Syntax

The syntax of set.difference() is

set.difference(other)

where

Parameter Description
other A set.

Examples

1 Difference of sets x, y

In the following program, we will take two sets: x, y; and find the difference of the sets: x - y.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'banana', 'mango'}
result = x.difference(y)
print(result)

Program Output

{'cherry', 'apple'}

2 Difference of sets x, y but x and y are disjoint sets

In the following program, we will find the difference of the sets: x - y. But x and y are disjoint sets. There are no common elements between x and y.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'guava', 'mango'}
result = x.difference(y)
print(result)

Program Output

{'banana', 'apple', 'cherry'}

Conclusion

In this Python Tutorial, we learned about Python set method difference(). We have gone through the syntax of difference() method, and its usage with example programs.