The python set difference function is used when you want to know the difference between two sets.
For example:
Let’s consider two sets P and Q. The set difference is the elements that are present in P but not Q.
If P = {1, 2, 3, 4}
Q = {2, 3, 9}
Then,
P – Q = {1, 4}
Q – P = {9}]
Syntax:
A.difference(B)
Return Value from difference()
The python set difference function returns the set difference between the two sets given by the user. It does not change the contents of the original sets.
Example 1: How does difference() work in Python?
In the program given below, we have found the set difference between set A and set B using the set difference built-in function.
Source Code
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
# Set difference of A-B
print(A.difference(B))
# Set difference of B-A
print(B.difference(A))
Output
{'b', 'a', 'd'}
{'g', 'f'}
Example 2: Set Difference Using – Operator
In the program given below we have found the set difference between two sets using the – operator. Here’s how:
Source Code:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A-B)
print(B-A)
Output
{'b', 'd', 'a'}
{'f', 'g'}
What is the set difference in Python?
Let us suppose there are two sets. Set X and set Y. Finding the set difference between the two sets is done using the set difference function in python.
When we identify the set difference X-Y, we’re looking for all the items in set X that aren’t in set Y. And vice versa when we are finding the set difference between Y-X.
How do you find the difference in sets in Python?
The set difference between two sets can be found using the set difference built-in function provided by the compiler.
Let us take two sets:
set Q = {5, 15, 10, 20, 30, 40, 50, 80}
set R = {100, 30, 80, 40, 150, 60, 70}
set Q – set R = {5, 15, 10, 20, 50}
set R – set Q = {100, 150, 60, 70}
Example program:
Source Code
a1 = {"apple", "strawberry", "cherry", "orange"}
b1 = {"google", "deloitte", "microsoft", "apple"}
z1 = a1.difference(b1)
print(z1)
Output:
{'orange', 'strawberry', 'cherry'}
What is set () in Python?
The set() in python converts a sequence of elements into sets.
Source Code
lis111 = [ 3, 4, 1, 4, 5 ]
# initializing the tuple
tup111 = (3, 4, 1, 4, 5)
print("Original list: " + str(lis111))
print("Original tuple: " + str(tup111))
print("New list : " + str(set(lis111)))
print("New tuple : " + str(set(tup111)))
Output:
Original list: [3, 4, 1, 4, 5]
Original tuple: (3, 4, 1, 4, 5)
New list: {1, 3, 4, 5}
New tuple: {1, 3, 4, 5}
How do you find the difference between the two sets?
The python set difference method is used to find the difference between two sets. The return value is the difference between the sets mentioned by the user.
Leave a Reply