The difference() method computes the difference of two sets and returns items that are unique to the first set.
Example
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()
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 AB.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,
Output
{'b', 'd', 'a'}
{'f', 'g'}
Here, we have used the - operator to compute the set difference of two sets A and B.