The difference() function in python helps to return the difference between two sets. Here the difference means the elements exist only in the first set, not in the second set. It doesn't make any changes to the original set.
A.difference(B) #where A & B are sets
The difference() function takes set as its parameter. We can say that this function is equal to A-B.
Parameter | Description | Required / Optional |
---|---|---|
A & B | The set to check for differences in | Required |
The return value is a set with some elements from the first set.
Input | Return Value |
---|---|
A & B | the new set(having elements in A not in B) |
A = {1, 2, 3, 4, 6}
B = {5, 2, 4, 7}
# Equivalent to A-B
print(A.difference(B))
# Equivalent to B-A
print(B.difference(A))
Output:
{1, 3, 6} {5, 7}
A = {1, 2, 3, 4, 6}
B = {5, 2, 4, 7}
print(A-B)
print(B-A)
Output:
{1, 3, 6} {5, 7}