Menu Close

Python Set difference Method

Python set difference

In this tutorial, you will learn all about Python set difference method which returns a set that contains differences between two sets. difference method is a set built-in method, which only used with the python set.

In the previous tutorial, we have seen Python set clear method to remove all items from the set.
To understand this tutorial, you should have basic knowledge of the Python set.

Python Set difference Method

Python set difference method is a built-in set method that returns a new set that contains the difference between two sets.

Note:- The returned set contains items that exist only first set, not both sets.

Syntax

The syntax of difference function in Python is:-

set.difference(set)

Parameter

The set difference method accepts one parameter that is set.

  • set:- Required. The set to check for difference.

Return Value

Python set difference method return new set.

Python set difference example

Here we will take some examples to understand difference function in python.

Example 1:

x = {'Python', 'C++', 'C', 'C#'}
y = {'HTML', 'C++', 'CSS', 'Bootstrap'}

result = x.difference(y)
print(result)

Output

{'C', 'C#', 'Python'}

Example 2:

x = {'Python', 'C++', 'C', 'C#'}
y = {'HTML', 'C++', 'CSS', 'Bootstrap'}

result = y.difference(x)
print(result)

Output

{'CSS', 'HTML', 'Bootstrap'}

Conclusion

In this tutorial, you have learned Python set difference method. difference function in Python returns a new set that contains items that only exist in the first set, not both sets.

I hope this tutorial will help you. If you like this article, please share it with your friends who want to learn Python programming.

Other set methods


For More Information:- Click Here

Python Set clear() Method
Python Set difference_update Method

Related Posts