Set of pythons | difference ()

Python Methods and Functions

The difference between two sets in Python is equal to the difference between the number of elements in the two sets. The difference () function returns a set, which is the difference between two sets. Let's try to figure out what is the difference between the two sets A and B. Then (set A — set B) will be elements present in set A, but not in B, and (set B — set A) will be the elements present. in set B, but not in set A.
Example:

 set A = {10, 20, 30, 40, 80} set B = {100, 30, 80, 40, 60 } set A - set B = {10, 20} set B - set A = {100, 60} Explanation: A - B is equal to the elements present in A but not in BB - A is equal to the elements present in B but not in A 

Let's take a look at the Venn diagram of the following difference set function.

Syntax :

  set_A.difference (set_B)  for (A - B)  set _B.difference (set_A )  for (B - A) 

In this program we will try to figure out the difference between the two sets set_A and set_B, both ways:

# Python code to get the difference between the two sets
# using the difference () between set A and set B

 
Driver code

A = { 10 , 20 , 30 , 40 , 80 }

B = { 100 , 30 , 80 , 40 , 60 }

print (A.difference (B))

print (B.difference (A))

Output:

 {10, 20} {100, 60} 

We can also use the - operator to find the difference between the two sets.

# Python code to get the difference between the two sets
# using the difference () between set A and set B

 
Driver code

A = { 10 , 20 , 30 , 40 , 80 }

< code class = "plain"> B = { 100 , 30 , 80 , 40 , 60 }

print (A - B)

print (B - A)

Exit :

 {10, 20} {100, 60} 




Tutorials