Python Set difference() Method

Returns a new set with items in the set that are not in other sets

Usage

The difference() method returns a new set of items that are in the original set but not in any of the specified sets.

You can specify as many sets as you want, just separate each set with a comma.

If you want to modify the original set instead of returning a new one, use difference_update() method.

Syntax

set.difference(set1,set2…)

Python set difference() method parameters
ParameterConditionDescription
set1, set2…OptionalA comma-separated list of one or more sets to find differences in

Basic Example

Example: Compute the difference between two sets

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

print(A.difference(B))

Output:

{'blue', 'green'}

Venn Diagram:

Set difference

Equivalent Operator

Set difference can be performed with the - operator as well.

Example:

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

# by method
print(A.difference(B))

# by operator
print(A - B)

Output:

{'blue', 'green'}

Difference between Multiple Sets

Multiple sets can be specified with either the operator or the method.

Example:

A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

# by method
print(A.difference(B,C))

# by operator
print(A - B - C)

Output:

{'green'}