Python .difference()
Published May 23, 2022
Contribute to Docs
The .difference() method returns a new set of objects unique to a given set when compared to others.
Syntax
The following syntaxes can be used:
set.difference(set1, set2, ..., setN)
setA - setB - setC
- The
.difference()method can be called directly againstsetwith multiple sets passed as arguments. - Optionally, the
-operator can be used between setssetA,setB, andsetCwhere it will return the same result as the.difference()method.
Example
The following example uses the - operator to create a new set of likes unique to sue_likes when compared with another set, erika_likes:
sue_likes = {'Pizza', 'Tofu', 'Poke'}erika_likes = {'Poke', 'Pizza', 'Popcorn'}print(sue_likes - erika_likes)
This would only print the items unique to the first set:
{'Tofu'}
Codebyte Example
In the example, a set of trips for the next year is created with the .difference() method:
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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours