Python .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.

  • 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

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

All contributors

Contribute to 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