Python Sets · Lesson 60 of 149

Python Set Operations

What you will learn

  • Union |, intersection &, difference - and symmetric difference ^
  • The method forms, and how they differ from the operators
  • Subset, superset and disjoint tests
  • The in-place forms such as |= and update
  • Combining many sets at once
  • Practical "who is in both?" questions

1. The four main operations

These are the operations of school mathematics, shown here with two sets:

a = {1, 2, 3, 4}
b = {3, 4, 5}

Picture them as two overlapping circles: a holds 1 2 3 4, b holds 3 4 5, and 3 4 sit in the overlap.

Operation Operator Method Meaning Result for a, b
union a | b a.union(b) in a or b (or both) {1, 2, 3, 4, 5}
intersection a & b a.intersection(b) in both {3, 4}
difference a - b a.difference(b) in a but not in b {1, 2}
symmetric difference a ^ b a.symmetric_difference(b) in exactly one of them {1, 2, 5}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(b - a))
print(sorted(a ^ b))
[1, 2, 3, 4, 5]
[3, 4]
[1, 2]
[5]
[1, 2, 5]

Notes:

  • Union and intersection are symmetric: a | b equals b | a.
  • Difference is not symmetric: a - b is {1, 2} but b - a is {5}.
  • Symmetric difference is the items in a - b together with b - a.
  • Every result is a new set; a and b are unchanged. (We use sorted only to print in a fixed order.)
Quick check: what is `{1, 2} & {2, 3}`?

{2}: the only item in both sets.

2. Operators or methods?

The operators need a set on both sides. The methods accept any collection (a list, a string, a range), and several at once:

print(sorted(a.union([9, 9], [8])))
print(sorted(a.intersection([3, 4, 99])))
print(sorted(a.difference([1, 2])))
print(sorted(a.union(b, {100}, [200])))
[1, 2, 3, 4, 8, 9]
[3, 4]
[3, 4]
[1, 2, 3, 4, 5, 100, 200]
a | [1]
TypeError: unsupported operand type(s) for |: 'set' and 'list'

Use the operators between two sets (short and readable), and the methods when the other side is not a set, or when you have more than two.

3. Subset, superset and disjoint

Sets can be compared by containment:

Test Operator Method True when
subset a <= b a.issubset(b) every item of a is in b
proper subset a < b subset, and b has more
superset a >= b a.issuperset(b) a contains every item of b
proper superset a > b superset, and a has more
disjoint a.isdisjoint(b) no items in common
x = {1, 2}
y = {1, 2, 3}
print(x <= y, x < y, y >= x, y > x)
print(x <= x, x < x)
print(x.issubset([1, 2, 5]), x.isdisjoint({3, 4}), x.isdisjoint({2, 3}))
True True True True
True False
True True False
  • A set is a subset of itself (x <= x), but not a proper subset (x < x).
  • x.isdisjoint({3, 4}) is true because they share nothing.
  • The empty set is a subset of every set: set() <= {1} is True.

These comparisons are not a total order. Two sets may be neither a subset nor a superset of each other: {1, 2} < {2, 3} and {1, 2} > {2, 3} are both False.

4. In-place versions

Each operation has a version that changes the set itself, instead of making a new one:

Operator Method Effect on s
s |= t s.update(t) adds the items of t
s &= t s.intersection_update(t) keeps only items also in t
s -= t s.difference_update(t) removes the items of t
s ^= t s.symmetric_difference_update(t) keeps items in exactly one
c = {1, 2, 3}
c |= {4}
print(sorted(c))
c &= {1, 2, 4, 9}
print(sorted(c))
c -= {1}
print(sorted(c))
c ^= {2, 7}
print(sorted(c))
[1, 2, 3, 4]
[1, 2, 4]
[2, 4]
[4, 7]

Compare f = e | {3} (a new set, e unchanged) with e |= {3} (the same set e grows). As with lists and dictionaries, it matters when other names point to the same set (lesson 2.7).

5. Many sets at once

Use the class methods with * to combine a whole list of sets (lesson 8.3 explained *):

allsets = [{1, 2}, {2, 3}, {2, 5}]
print(sorted(set().union(*allsets)))
print(sorted(set.intersection(*allsets)))
[1, 2, 3, 5]
[2]
  • set().union(*allsets) is every item that appears anywhere.
  • set.intersection(*allsets) is the items that appear in all of them.

6. Counting with the operations

A few useful facts, which you can check with the example sets:

print(len(a | b) == len(a) + len(b) - len(a & b))
print(len(a ^ b) == len(a - b) + len(b - a))
print(sorted((a | b) - (a & b)) == sorted(a ^ b))
True
True
True

The size of a union is the sizes added, minus the overlap that was counted twice. And the symmetric difference is the union without the intersection.

7. Dictionary views are set-like

The keys and items views of a dictionary support the same operators (lesson 9.2):

d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
print(sorted(d1.keys() & d2.keys()))
print(sorted(d1.keys() - d2.keys()))
print(d1.items() & {("a", 1)})
['b']
['a']
{('a', 1)}

This finds keys that two dictionaries share, or pairs that match exactly.

Worked example: course enrolments

Three students are in the maths course, and three in another course. Answer some questions with set operations.

students = {"Rina", "Sam", "Lee"}
maths = {"Rina", "Lee", "Mia"}

print(sorted(students & maths))
print(sorted(students | maths))
print(sorted(students - maths))
print(sorted(maths - students))
print(sorted(students ^ maths))

required = {"name", "email"}
given = {"name", "age"}
print(sorted(required - given), required <= given)
['Lee', 'Rina']
['Lee', 'Mia', 'Rina', 'Sam']
['Sam']
['Mia']
['Mia', 'Sam']
['email'] False
Question Expression Answer
who is in both courses? students & maths Lee, Rina
everyone, once students | maths four people
in the first only students - maths Sam
in the second only maths - students Mia
in exactly one students ^ maths Mia, Sam
which required fields are missing? required - given email
are all required fields given? required <= given False

The second part, required - given, is a neat way to validate a form: whatever remains is missing. The names and fields are made up.

Common mistakes

  • Using |, & or - with a list on one side. Make it a set, or use the method form.
  • Expecting a - b to equal b - a.
  • Thinking <= and > give a full ordering. Two sets can be unrelated.
  • Using s | t and expecting s to change. Use s |= t or s.update(t).
  • Using {} as the starting empty value for a union. Start from set().

Key takeaways

  • | union, & intersection, - difference, ^ symmetric difference; each makes a new set.
  • The operators need sets on both sides; the methods (union, intersection, ...) accept any collection and several arguments.
  • <=, <, >=, > and isdisjoint test containment and overlap.
  • |=, &=, -=, ^= and the *_update methods change a set in place.
  • set().union(*sets) and set.intersection(*sets) combine many sets at once.

Practice

1. With a = {1, 2, 3} and b = {2, 3, 4}, what are a | b, a & b, a - b and a ^ b?

Show answer

{1, 2, 3, 4}, {2, 3}, {1} and {1, 4}.

2. Is {1, 2} < {1, 2} true? And {1, 2} <= {1, 2}?

Show answer

False and True. A set is a subset of itself, but not a proper subset.

3. Find the items of the list [1, 2, 3, 4] that are not in {2, 4}, as a set.

Show answer

set([1, 2, 3, 4]) - {2, 4} gives {1, 3}. Or use the method on a set: {1, 2, 3, 4}.difference({2, 4}).

4. Do {1, 2} and {3, 4} share any items? Write the test.

Show answer

{1, 2}.isdisjoint({3, 4}) is True, so they share nothing.

5. Which words are in both ["a", "b", "c"] and ["b", "c", "d"]?

Show answer

set(["a", "b", "c"]) & set(["b", "c", "d"]) gives {'b', 'c'}.

6. What is the difference between s | t and s |= t?

Show answer

s | t makes a new set and leaves s alone. s |= t adds the items of t to s itself.