Skip to content

Module 8 · Python Data Structures — topic 13 of 22

Set operations

Combine and compare sets with union, intersection, difference and symmetric difference, using operators or methods, and test relationships with subset, superset and disjoint checks.

Beginner 12 min read·Lesson 116 of 306 in Python Programming

Learning objectives

  • Apply the four main set operations
  • Choose between operators and methods
  • Test subset, superset and disjoint relationships

Definition

Combine and compare sets with union, intersection, difference and symmetric difference, using operators or methods, and test relationships with subset, superset and disjoint checks.

Introduction

Sets support the operations from school mathematics. Given two groups, you can combine them, find what they share, find what one has that the other doesn’t, or find what is in exactly one of them. The next three lessons look at union, intersection and difference individually.

Why it matters

Questions such as “which students take both courses?”, “which products are missing from the warehouse?” and “which permissions does this role have that the other lacks?” are each a single set operation.

Detailed explanation

OperationOperatorMethodResult
Uniona | ba.union(b)items in either
Intersectiona & ba.intersection(b)items in both
Differencea - ba.difference(b)items in a but not b
Symmetric differencea ^ ba.symmetric_difference(b)items in exactly one

Operators require both operands to be sets; methods accept any iterable, such as a list.

All four return a new set. In-place forms update the left set: |=, &=, -=, ^= or update(), intersection_update() and so on.

Relationship tests: a <= b (a.issubset(b)) is True if every item of a is in b; a >= b tests superset; a.isdisjoint(b) is True if they share nothing.

Difference is not symmetric: a - b and b - a usually differ.

The results are unordered, so sort them for display.

Syntax

Text
a | b a & b a - b a ^ b
a <= b a >= b a.isdisjoint(b)
  • Operators work on two sets.
  • Methods accept any iterable.
  • Comparisons test subset and superset.

Code examples

The four operations

Python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b), sorted(b - a))
print(sorted(a ^ b))
Output
[1, 2, 3, 4, 5]
[3, 4]
[1, 2] [5]
[1, 2, 5]

Relationships

Python
basic = {"read"}
editor = {"read", "write"}
admin = {"read", "write", "delete"}
print(basic <= editor, editor <= admin, admin <= editor)
print(editor.isdisjoint({"delete"}))
Output
True True False
True

More examples

Comparing course enrolments

Python
python = {"Asha", "Ben", "Chen", "Dev"}
data = {"Chen", "Dev", "Esha"}
print("Both courses:", sorted(python & data))
print("Any course:", len(python | data))
print("Only Python:", sorted(python - data))
print("Exactly one:", sorted(python ^ data))
waitlist = ["Esha", "Farah"]
print("Waitlist not enrolled anywhere:", sorted(set(waitlist) - (python | data)))
print("Union with a list via method:", len(python.union(waitlist)))
Output
Both courses: ['Chen', 'Dev']
Any course: 5
Only Python: ['Asha', 'Ben']
Exactly one: ['Asha', 'Ben', 'Esha']
Waitlist not enrolled anywhere: ['Farah']
Union with a list via method: 6

Step-by-step explanation

  • & finds students in both courses.
  • | combines everyone, counting each student once.
  • - and ^ find students in only one particular course or in exactly one course.
  • Converting the waitlist to a set lets it be compared with an operator; union() accepts the list directly.

Expected output

Running “Comparing course enrolments” prints exactly:

TextOutput
Both courses: ['Chen', 'Dev']
Any course: 5
Only Python: ['Asha', 'Ben']
Exactly one: ['Asha', 'Ben', 'Esha']
Waitlist not enrolled anywhere: ['Farah']
Union with a list via method: 6

Practical applications

  • Access-control systems compare permission sets with subset checks.
  • Inventory reconciliation uses difference to find missing items.
  • Recommendation engines use intersection to find shared interests.

Best practices

  • Use operators for set-to-set work and methods for other iterables.
  • Name results by meaning: in_both, only_in_a.
  • Sort set results before showing them to users.

Common mistakes

Using an operator with a list

Avoid

{1, 2} | [3]

Prefer

{1, 2} | {3} # or {1, 2}.union([3])

Set operators need sets on both sides; methods accept other iterables.

Expecting difference to be symmetric

Avoid

missing = shipped - ordered # meant the other way

Prefer

missing = ordered - shipped

a - b keeps items of a; think about which set you start from.

Key takeaways

  • | union, & intersection, - difference, ^ symmetric difference.
  • Methods accept any iterable; operators need sets.
  • <=, >= and isdisjoint test relationships.

Try it yourself

  1. 1
    Given the letters of two words, find the letters they share and the letters unique to each.
  2. 2
    Check whether every required skill in a set is present in a candidate’s skill set.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic