difference_update() of Sets in Python

difference_update() of Sets in Python 

This method helps to find out the difference between two sets. The difference_update() method is same as the difference() method in Python sets. The only difference is that difference() method returns a new set whereas difference_update() method updates the calling set.

difference_update of sets in python

difference_update() of Sets

In Python, The difference_update() method is used to update a set by removing elements that are common to both the calling set and another specified set. This method modifies the original set in place and does not create a new set. It essentially performs the set difference operation and updates the calling set with the result.

Python Set difference_update()
Let us understand this with an example:
  • set A = { 1, 2, 3, 4, 5 }
  • set B = { 1, 3, 5, 7 }

For A – B

  • A.difference(B)               # It will return a new set having i.e. newSet = { 2, 4 }
  • A.difference_update(B) # It will update the set A with A-B i.e. set A = { 2, 4 }

For B – A

  • B.difference(A)               # It will return a new set having i.e. newSet = { 7 }
  • B.difference_update(A) # It will update the set B with B-A i.e.  set B = { 7 }

Syntax :


set1.difference_update(set2)

Return Type :

  • difference_update() method does not return any value. So it returns None.
  • It only changes the values of existing set.
Run
#difference of sets using difference_update() method

#  A - B will be updates in set A
A = { 1, 2, 3, 4, 5, 6 }
B = { 2, 4, 6, 8, 10 }
print( A.difference_update(B) )   #returns NONE
print(A)    # set A is updated
print(B)    # set B remained same

#  B - A will be updates in set B
A = { 1, 2, 3, 4, 5, 6 }
B = { 2, 4, 6, 8, 10 }
print( B.difference_update(A) )   #returns NONE
print(A)    # set A remained same
print(B)    # set B is updated
 Output :

 None
 {1, 3, 5}
 {2, 4, 6, 8, 10}

 None
 {1, 2, 3, 4, 5, 6}
 {8, 10}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription