Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Set difference_update() method



The Python Set difference_update() method is used to remove elements from the set that are also present in one or more specified sets by altering the original set.

It modifies the set in place effectively by updating it with the difference between itself and one or more other sets. This method removes all elements from the original set that are common to the specified set(s).

The difference() method returns a new set where as the difference_update() method directly modifies the original set. It efficiently updates the set by iterating through the elements of the specified set and removing any matching elements from the original set.

Syntax

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

set.difference_update(*others)

Parameters

This method accepts the following parameter −

  • others: One or more sets or iterables whose elements will be removed from the original set.
  • Return value

    This method returns new set containing.

    Example 1

    Following is the example of python set difference_update() method, which shows updating a set by removing elements that present in another set −

    # Define a set
    set1 = {1, 2, 3, 4}
    set2 = {3, 4, 5}
    
    # Update set1 by removing elements present in set2
    set1.difference_update(set2)
    
    print(set1)  
    

    Output

    {1, 2}
    

    Example 2

    We can find the difference between the multiple sets i.e more than one and update the difference result with the help of difference_update() method. In the below example we are finding the difference between three sets and updating the result −

    # Define a set
    my_set = {1, 2, 3, 4}
    set2 = {3, 4, 5}
    set3 = {4, 5, 6}
    
    # Update the set by removing elements present in set2 and set3
    my_set.difference_update(set2, set3)
    
    print(my_set)  
    

    Output

    {1, 2}
    

    Example 3

    This example shows how to update a set by removing elements present in an iterable such as list, tuple.

    # Define a set
    my_set = {1, 2, 3, 4}
    my_list = [3, 4]
    
    # Update the set by removing elements present in the list
    my_set.difference_update(my_list)
    
    print(my_set)   
    

    Output

    {1, 2}
    

    Example 4

    When we apply the difference_update() method on a set with elements and an empty set then the result will be the set with elements. In this example we are updating the original set with an empty set which has no effect on the set −

    # Define a set
    my_set = {1, 2, 3}
    
    # Update the set with an empty set
    my_set.difference_update(set())
    
    print(my_set)
    

    Output

    {1, 2, 3}
    
    python_set_methods.htm
    Advertisements