.difference_update()
Published May 29, 2024
Contribute to Docs
In Python, the .difference_update()
method modifies a set by removing all elements present in another set, keeping only the ones that are not found in the other one. Unlike the .difference()
method, which returns a new set, .difference_update()
changes the original set in place.
Syntax
set.difference_update(set1, set2, ..., setN)
set
: The set to be modified.set1, set2, ..., setN
: The set(s) whose elements are to be removed from the original set.
Example
In this example, the set salad
is modified using the .difference_update()
method to remove elements also present in the larder
set. After the operation, the salad
set will only contain elements not found in the larder
set:
salad = {'lettuce', 'beetroot', 'walnuts', 'cheese', 'seeds'}larder = {'tomatoes', 'lettuce', 'cheese', 'seeds', 'celery'}salad.difference_update(larder)print(salad)
The above example produces the following output:
{'walnuts', 'beetroot'}
Codebyte Example
In the below codebyte example, the salad
set has elements removed if they are found in larder
, shopping1
, or shopping2
sets, leaving unique elements in the salad
set:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours