Python Set Difference Tutorial with Programs and Example 

In this tutorial, you will learn about the Python Set difference method with the help of programs and examples.

The sets difference is similar to the difference between the two sets of the number of elements. The difference() function returns a set that is the difference between two sets.

Example:

set A = {1, 2, 3, 4, 8}
set B = {1, 3, 8, 4, 6}

set A - set B = {2, 6}
set B - set A = {6}

Explanation: 
A - B is equal to the elements present in A but not in B
B - A is equal to the elements present in B but not in A  

What is Python set difference?

Python set difference method is an operation that returns a set containing the difference between two sets. The returned set comprises just those elements that exist in the first set, not in both.

Further, Python includes a set data structure for implementing sets. In addition, it provides a variety of additional functions that facilitate common set operations such as union, intersection, difference, etc.

difference() Syntax

A.difference(B)

Here, A and B represent two sets.

difference() Parameter

The method difference() accepts a single argument:

  • B- a set whose elements are not contained in the final set.

difference() Return Value

The difference() method returns:

  • a set with elements unique to the first original sets.

Set difference() Python example

A = {'red', 'white', 'yellow', 'blue'}
B = {'blue', 'red', 'green'}

print(A.difference(B))

print(B.difference(A))

Output

{'yellow', 'white'}
{'green'}

In the preceding example, we utilized the difference() method to compute the set differences between two sets A and B.

Here is how it works:

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

Set difference python Using Operator

Another way to determine the set difference in Python is by using an operator.

For example:

A = {'apple', 'orange', 'kiwi', 'atis'}
B = {'atis', 'grapes', 'lemon'}

print(A - B)

print(B - A)

Output

{'orange', 'kiwi', 'apple'}
{'grapes', 'lemon'}

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

How do you print the difference between two sets in Python?

In this program, we will try to find out how to print the difference between two sets in Python.

A = {2, 4, 6, 8, 10}
B = {4, 6, 8, 10, 12}

print(A.difference(B))
print(B.difference(A))

Output

{2}
{12}

Conclusion

Python is well-known for its simple, English-like syntax. Python offers us a vast number of built-in functions that allow us to do many major set operations.

  • A difference between two sets returns a new set that has elements from the first set that are not present in the second set.
  • Use the set difference() method or set difference operator (-) to find the difference between sets.

Leave a Comment