.difference()

BrandonDusch's avatar
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 against set with multiple sets passed as arguments.
  • Optionally, the - operator can be used between sets setA, setB, and setC where 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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy