Latest Code Tutorials

Python Set difference_update() Method Example


Python Set difference_update() is an inbuilt method that finds the difference of two sets; also it modifies the caller set with the result set. In the set difference method, we find the difference between the two sets and returns the difference as a new set.

For example,

if  A = {a,b,c,d,e,f} and B={a,e,f,g} are two sets and if we want to find A-B then the result will be {b,c,d}, also this method will modify the set A with values {b,c,d}.

Python Set difference_update() Method

Similarly, if we want to find B-A, then the result will be {f,g}, and this method will modify the set B with this value, but set A will remain unchanged.

Python Set difference_update() Method

Python difference_update() method helps in the in-place way of differentiating the set. The previously discussed Python set difference() helps to find out the difference between two sets and returns the new set with a different value, but the difference_update() updates the existing caller set.



The above syntax will help us to find the difference between First_Set-Second_Set.

So, If we want to find A-B, the syntax will be:


Return Value

The function does not return any value, and it returns None. But it changes the value of the caller set.

See the following code example.


# Declaring two sets
A = {'a', 'b', 'c', 'd', 'e'}
B = {'a', 'e', 'f', 'g'}

# Now we will apply difference_update() to find A-B
result = A.difference_update(B)

# Now we will check the value of A, B, and result
print("Value of A is: ", A)
print("Value of B is: ", B)
print("Value of result is: ", result)


Value of A is:  {'c', 'b', 'd'}
Value of B is:  {'f', 'e', 'a', 'g'}
Value of result is:  None

From the above example, we can see that we could find the difference between set A and B, but the method modified the value of set A with the value of A-B. Also, B remains unchanged, and the value of the result is None as the function does not return anything.

See also

Python set copy()

Python set clear()

Python set add()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.