difference_update method of set in Python

The difference_update() method of set class updates a set object by removing the elements in it which is specified through another set.

Set Updated 22 Jul 2021 1 min read

Overview

  • The method difference_update() removes elements of a set as specified by the another set.
  • In other words, the difference between the original set and another set is calculated, which is updated as the contents of the original set.

Example

python
# Example Python program that removes

            # the elements from a set as specified by another set

            brass   = {"Trumpet", "Bugle", "French Horn", "Bass Trambone", "Piccola Trumpet", "Tuba"}

            remove  = {"Piccola Trumpet"}

            print("Brass instruments:")

            print(brass)

# Remove a set of instruments

            brass.difference_update(remove)

# Print the new set

            print("New brass instruments:")

            print(brass)

Output

Output
Brass instruments:

{'Tuba', 'Piccola Trumpet', 'Bugle', 'Trumpet', 'Bass Trambone', 'French Horn'}

New brass instruments:

{'Tuba', 'Bugle', 'Trumpet', 'Bass Trambone', 'French Horn'}