Python Set difference()

The difference() method computes the difference of two sets and returns items that are unique to the first set.

Example

# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}

# returns items present only in set A print(A.difference(B))
# Output: {1, 9}

difference() Syntax

The syntax of the difference() method is:

A.difference(B)

Here, A and B are two sets.


difference() Parameter

The difference() method takes a single argument:

  • B - a set whose items are not included in the resulting set

difference() Return Value

The difference() method returns:

  • a set with elements unique to the first set

Example 1: Python Set difference()

A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}

# equivalent to A-B print(A.difference(B)) # equivalent to B-A print(B.difference(A))

Output

Set Difference (A - B) = {'b', 'a', 'd'}
Set Difference (B - A) = {'g', 'f'}

In the above example, we have used the difference() method to compute the set differences of two sets A and B. Here,

  • A.difference(B) - returns a set with elements unique to set A
  • B.difference(A) - returns a set with elements unique to set B

Note: Mathematically, the operation A.difference(B) is equivalent to A - B.


Example 2: Set Difference Using - Operator

We can also find the set difference using - operator in Python. For example,

A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}

# prints the items of A that are not present in B
print(A - B)

# prints the items of B that are not present in A
print(B - A)

Output

{'b', 'd', 'a'} 
{'f', 'g'}

Here, we have used the - operator to compute the set difference of two sets A and B.

Did you find this article helpful?