The Set difference() method finds the difference between two sets. It returns a new set that contains all the elements of the first set that are not present in the second set.
Syntax
my_set.difference(set1, set2, ...)difference() Parameters
Python Set difference() method parameters:
| Parameter | Condition | Description |
|---|---|---|
set1, set2, ... |
Optional | A comma-separated list of one or more sets to find differences in |
difference() Return Value
Python Set difference() method returns a set with elements unique to the first set.
Examples
Example 1: Difference between Two Sets
A = {'Tom', 'Anna', 'David'}
B = {'David', 'Tom'}
result = A.difference(B)
print(result) # Output: {'Anna'}output
{'Anna'}Example 2: Difference between Multiple Sets
The difference() method allows to compute the difference between multiple sets:
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
result = A.difference(B, C)
print(result) # Output: {1, 2}output
{1, 2}Example 3: Difference between a Set and a List
You can also pass iterables like list: difference() first converts the iterables to sets and then computes the difference.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ['d', 'e', 'f']
result = A.difference(B)
print(result) # Output: {'i', 'a', 'o', 'u'}output
{'i', 'a', 'o', 'u'}Example 4: Difference between a Set and a Tuple
You can also pass iterables like tuple: difference() first converts the iterables to sets and then computes the difference.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ('d', 'e', 'f')
result = A.difference(B)
print(result) # Output: {'i', 'a', 'o', 'u'}output
{'i', 'a', 'o', 'u'}Example 5: Difference between a Set and a Dictionary
You can also pass iterables like dictionary: difference() first converts the iterables to sets and then computes the difference.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = {1: 'd', 2: 'e', 3: 'f'}
C = {'d': 1, 'e': 2, 'f': 3}
print(A.difference(B)) # Output: {'o', 'e', 'i', 'a', 'u'}
print(A.difference(C)) # Output: {'o', 'a', 'u', 'i'}output
{'o', 'e', 'i', 'a', 'u'}
{'o', 'a', 'u', 'i'}Example 6: Difference between a Set and a String
You can also pass iterables like string: difference() first converts the iterables to sets and then computes the difference.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = 'def'
print(A.difference(B)) # Output: {'i', 'a', 'o', 'u'}output
{'i', 'a', 'o', 'u'}Equivalent Operator – for difference()
Set difference can be performed with the - operator as well, providing an alternative to the difference() method.
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
print(A.difference(B)) # Output: {1, 2}
print(A - B) # Output: {1, 2}output
{1, 2}
{1, 2}Of course, you can use the - operator with multiple sets:
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
print(A.difference(B, C)) # Output: {1, 2}
print(A - B - C) # Output: {1, 2}output
{1, 2}
{1, 2}