Python Set difference() method



The Python Set difference() method is used with sets to return a new set containing elements that are present in the first set but not in any of the other sets provided as arguments. It effectively performs a subtraction operation on sets removing elements that appear in the subsequent sets. For example set1.difference(set2) returns a set with elements that are in set1 but not in set2. This method helps in identifying unique elements of a set relative to others by maintaining the property of sets to hold only distinct items.

Syntax

Following is the syntax and parameters of Python Set difference() method −

set1.difference(*others)

Parameter

This function accepts variable number of set objects as parameters.

Return value

This method does not return any value.

Example 1

Following is the basic example which shows the usage of the python set difference() method for comparing the sets −

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

result = set1.difference(set2)
print(result)  

Output

{1, 2}

Example 2

In sets we can find the difference of more than two sets at a time. In this example we are using the difference() method for finding the difference between three sets −

set1 = {1, 2, 3, 4, 5}
set2 = {2, 3}
set3 = {4, 5}

result = set1.difference(set2, set3)
print(result)   

Output

{1}

Example 3

When we try to find the difference between a set with elements and an empty set then it returns the original set and here is the example of it−

set1 = {1, 2, 3}
set2 = set()

result = set1.difference(set2)
print(result)  

Output

{1, 2, 3}

Example 4

Here in this example, as there are no common elements between set1 and set2 so the result is just set1 −

set1 = {1, 2, 3}
set2 = {4, 5, 6}

result = set1.difference(set2)
print(result)  

Output

{1, 2, 3}
python_set_methods.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy