Tutorial Study Image

Python difference()

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
 

difference() Parameters:

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

difference() Return Value

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)

Examples of difference() method in Python

Example 1: How difference() method works in Python?


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}

Example 2: How to find Set difference using - Operator?


A = {1, 2, 3, 4, 6}
B = {5, 2, 4, 7}
print(A-B)

print(B-A)
 

Output:


{1, 3, 6}
{5, 7}