# Python Set difference() method

The python set difference() method is used to show the difference between two set elements as you learn in mathematics. First now understand,

## How the Python difference() method works

Suppose we have the following two sets :

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

The difference between A and B is,
A-B = {4,5,6}

Firstly remove the common elements. Now, the element left in the first set is your answer. As we can see in the above example, In set A and B {1,2,3} are common so remove that. Now, the first set (A) is left with {4,5,6} element i.e our answer.

The difference between B and A is,
B-A = {8,7}

As we can see, in the python set A and B {1,2,3} elements are common so remove that. Now, the first set (B) is left with {8,7} element i.e our answer.

Note: 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.

## Python difference() method Syntax :

``Firstset.difference(second set) ``

As per the above syntax, we can write as below.

A.difference(B) that means A-B
B.difference(A) that means B-A

Now, let’s understand with the help of examples.

### Example 1:

``````A={12,3,4,6}
B={12,9,10,11}
print("A-B is",A.difference(B))
print("B-A is",B.difference(A))``````

### Output :

``````A-B is {3, 4, 6}
B-A is {9, 10, 11}``````

### Example 2:

``````A={12,3,4,6}

B={12,9,10,11}

print(A-B)``````

### Output :

``{3, 4, 6}``

If all elements of the first set are present in the second set then it will return the null set (empty set).

### Example 3:

``````A={12,4,6}
B={12,4,6,9,10,11}
print("A-B is" ,A-B)
print("B-A is", B-A)``````

### Output :

``````A-B is set()
B-A is {9, 10, 11}``````

## Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

### Python Online Quiz

Level up your coding skills with our interactive programming quiz!