Python Set difference_update():

The difference_update() method updates the set by removing an element common with the other sets. In other words, it keeps the unique element of the caller set while deleting all the duplicate elements with set as parameters. For example, this method will delete all the elements from set A that are also an element of Set B.

Method signature

The signature for the difference_update() method is as shown below. At this point, we are updating set “s1” to contain none of the elements present in set “s2”.

s1.difference_update(s2,s3,...)

Method parameters and return type

  • The difference_update() takes zero or more parameters. This parameter can be a data element, set, list, tuple, or dictionary.
  • However, this method doesn’t return anything.

Python Set difference_update Examples:

Example 1: In this example, let us take a set s1, set s2 and set s3 with numbers. Here, we are finding the difference update with two set at same time.

#Initializing the Set
s1={8,311,98,36,15}
s2={6,8,36}
s3={2,311,5,6}
#Printing a result
print("Before update s1 is ",s1)
# Performing update
s1.difference_update(s2,s3)
#Printing a result
print("After update s1 is ",s1)

Output

Before update s1 is  {98, 36, 8, 15, 311}
After update s1 is  {98, 15}

Example 2:

For this example, let us take a set containing cities to be visited by the salesman. Additionally, we take set “s1” and “s2” who will be visiting some city. Now, to find the list of cities that any salesman will not visit, we can use this method.

#Initializing the Set
city={"Delhi", "Mumbai","Hyderabad","Pune","Jaipur","Indore"}
s1={"Mumbai","Pune"}
s2={"Delhi","Jaipur"}
#Using difference_update method
city.difference_update(s1,s2)
#Printing a result
print("Cities that will not be visited by any salesman are",city)

Output

Cities that will not be visited by any salesman are {'Hyderabad', 'Indore'}

Example 3: In this example, let us demonstrate this method using tuple, list and dictionary. So, All common elements from tuples, lists, and dictionaries will be removed from the set. Consequently, all of the values from sets “s2” and “s3” that are common to set s1 are removed from set s1.

#Initializing the Set
s1={10,22,30,34,55,85,"Name"}
#Initializing the list, tuple and dictionary
l1=[12,34,22]
t1=(55,65,85)
d1={"Name":"John","Salary":50000,"Experience":10}
#Using difference_update method and printing 
s1.difference_update(l1,t1,d1)
print("Set after removing common data from list, tuple, dictionary ",s1)

Output

Set after removing common data from list, tuple, dictionary {10, 30}

Conclusion

The difference_update method updates the original set by removing the common element with other sets passed as a parameter.

References

Happy Learning 🙂

Leave A Comment