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

# Compute the difference between two sets
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

print(A.difference(B))
# Prints {'blue', 'green'}
Set difference

Equivalent Operator

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

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

# by method
print(A.difference(B))
# Prints {'blue', 'green'}

# by operator
print(A - B)
# Prints {'blue', 'green'}

Difference between Multiple Sets

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

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

# by method
print(A.difference(B,C))
# Prints {'green'}

# by operator
print(A - B - C)
# Prints {'green'}