Content · Programming · Python

Python set.difference Method: Usage and Examples

set.difference(*others) returns a new set containing elements present in the original but absent from every other iterable. It leaves the source set unchanged. See two practical examples, edge cases and common mistakes.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A list of enrolled students excludes those who withdrew.

What You Need to Understand


set.difference(*others) returns a new set containing elements present in the original but absent from every other iterable. It leaves the source set unchanged.

When to Use It


A list of enrolled students excludes those who withdrew.

Step-by-Step Python Example


enrolled = {"Maya", "Noa", "Liam"}
withdrawn = {"Noa"}
remaining = enrolled.difference(withdrawn)
print(sorted(remaining))
print(sorted(enrolled))

How the Example Works


Noa is absent from the new set, while the original still contains all three students.

Example Output


['Liam', 'Maya']
['Liam', 'Maya', 'Noa']
[1, 3]

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

online = {1, 2, 3}
local = {2}
print(sorted(online.difference(local)))

Important Behavior and Edge Cases


Difference is directional. A.difference(B) and B.difference(A) usually produce different results.

Try It Yourself


Calculate products available online but not in a local store.

Common Beginner Mistakes


  • Difference is directional. A.difference(B) and B.difference(A) usually produce different results.
  • Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.

Key Takeaways


  • set.difference(*others) returns a new set containing elements present in the original but absent from every other iterable.
  • Noa is absent from the new set, while the original still contains all three students.
  • Difference is directional.
Share this resourceSend this page to someone who may find it useful.