Intermediate   Chapter 50 · 30 min read · Module 4: Python Data Structures

Set Methods

Learning objectives
  • After this chapter you can add and remove items with add, update, remove, discard, pop and clear.
  • You can explain the difference between remove and discard.
  • You can use union, intersection, difference and symmetric_difference as methods.
  • You can use the in-place update variants and know when to choose them.
  • You can test relations with issubset, issuperset and isdisjoint.

A set is mutable, so it has methods that change it, and it has methods that compare it with other sets. In the last chapter you used operators such as | and &. Every one of these has a method form with a name that is easier to read, and the methods have one extra advantage: they accept any iterable, not only sets.

In this chapter you will learn the methods in three groups. First come the methods that add and remove items. Then come the methods that build a new set from two sets. Last come the methods that test how two sets are related.

Throughout the examples we print sorted(...) of a set, because the order of a set is not guaranteed.

Adding items

s.add(x) adds one item. If the item is already there, nothing happens. s.update(iterable) adds every item from an iterable such as a list, a tuple, a string or another set. Note that update with a string adds each character, so s.update("hi") adds 'h' and 'i', not 'hi'.

Example 1: add and update
s = {1, 2}
s.add(3)
s.add(3)
print(sorted(s))
s.update([3, 4, 5], (6,))
print(sorted(s))
t = set()
t.update("hi")
print(sorted(t))
t.add("hi")
print(len(t))
[1, 2, 3] [1, 2, 3, 4, 5, 6] ['h', 'i'] 3

Since the set already ignores duplicates, you never need to check whether an item is there before adding it. This makes sets a tidy way to collect values in a loop: create an empty set, call add for each value, and at the end you hold each distinct value exactly once. The cost of each add is small, even when the set grows large.

Removing items

MethodWhat it doesIf the item is missing
remove(x)removes xraises KeyError
discard(x)removes xdoes nothing
pop()removes and returns an arbitrary itemraises KeyError if the set is empty
clear()removes all itemsdoes nothing

Choose discard when you do not care whether the item exists. Choose remove when a missing item would mean a bug and you want to know about it. pop() removes an item you cannot choose, because sets have no order. Do not use it when you need a specific item; it is useful when you want to process items one by one until the set is empty.

Example 2: removing
s = {10, 20, 30, 40}
s.remove(10)
s.discard(20)
s.discard(99)
print(sorted(s))
try:
    s.remove(99)
except KeyError:
    print("KeyError for remove")
single = {7}
print(single.pop())
print(len(single))
s.clear()
print(s)
print(len(set()))
[30, 40] KeyError for remove 7 0 set() 0

Methods that build a new set

union, intersection, difference and symmetric_difference give a new set and leave the originals unchanged. The first three accept more than one argument, so a.union(b, c) joins three groups. Unlike the operators, the methods also accept lists and other iterables.

Example 3: set algebra with methods
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a.union(b, [9])))
print(sorted(a.intersection(b)))
print(sorted(a.difference(b)))
print(sorted(a.symmetric_difference(b)))
print(sorted(a.intersection([2, 4, 6])))
print(sorted(a))
[1, 2, 3, 4, 5, 9] [3, 4] [1, 2] [1, 2, 5] [2, 4] [1, 2, 3, 4]
a | [1] raises TypeError because the operator needs two sets, but a.union([1]) works. This is a nice reason to learn both forms.

In-place update methods

Each algebra method has a version that changes the set itself and returns None: update (union), intersection_update, difference_update and symmetric_difference_update. They are equal to the operators |=, &=, -= and ^=. A common mistake is writing s = s.update(x), which sets s to None.

Example 4: changing a set in place
s = {1, 2, 3, 4, 5}
s.intersection_update({2, 3, 4, 9})
print(sorted(s))
s.difference_update({4})
print(sorted(s))
s.symmetric_difference_update({3, 8})
print(sorted(s))
result = s.update([100])
print(result)
[2, 3, 4] [2, 3] [2, 8] None

Testing relations and copying

a.issubset(b) is true when every item of a is in b. a.issuperset(b) is the reverse. a.isdisjoint(b) is true when the sets share nothing. A set is a subset of itself, and the empty set is a subset of every set. Use copy() to make a separate set; a plain assignment b = a gives two names for the same set.

Example 5: relations and copies
small = {1, 2}
big = {1, 2, 3}
print(small.issubset(big), big.issuperset(small))
print(big.issubset(small), small.isdisjoint({7, 8}))
print(set().issubset(small), small.issubset(small))
same = big
copy = big.copy()
big.add(4)
print(sorted(same))
print(sorted(copy))
True True False True True True [1, 2, 3, 4] [1, 2, 3]

When a method takes several arguments, Python handles them from left to right. So a.difference(b, c) removes the items of both b and c from a, which is the same as a - b - c. Knowing this helps you replace a long chain of loops with one clear line.

Which form should you pick, the operator or the method? Operators such as | and & are short and good when both sides are sets. Methods are better when one side is a list or a tuple, when you want to combine more than two groups, or when you want the code to read like plain English. Many teams prefer methods in larger programs because the name says exactly what happens, for example intersection_update is much clearer to a new reader than &=.

A short worked example

Imagine a quiz where you must find which students have submitted. You keep a set of all students and a set of those who have submitted. The students who have not submitted are all.difference(done). As each late student sends work, you call discard on a copy of the missing set. This style is shorter and faster than looping with lists.

Example 6: who is missing
everyone = {"Asha", "Ravi", "Mina", "Tom"}
done = {"Ravi", "Tom"}
missing = everyone.difference(done)
print(sorted(missing))
missing.discard("Asha")
print(sorted(missing))
print(everyone.issuperset(done))
['Asha', 'Mina'] ['Mina'] True

Python syntax

Syntax
s.add(x)  s.update(iterable)
Syntax
s.remove(x)  s.discard(x)  s.pop()  s.clear()
Syntax
a.union(b)  a.intersection(b)  a.difference(b)  a.symmetric_difference(b)
Syntax
a.update(b)  a.intersection_update(b)  a.difference_update(b)
Syntax
a.issubset(b)  a.issuperset(b)  a.isdisjoint(b)  a.copy()

Real-world applications

  • Tracking which users have completed a task.
  • Removing banned words from a list of tags.
  • Finding the items two shopping carts have in common.
  • Keeping a set of already-visited pages or nodes.

Common mistakes

Mistake: Using remove on an item that may be missing.
Fix: Use discard, or check with in first.
Mistake: Writing s = s.update(other) or s = s.add(1).
Fix: These methods return None. Call them on their own line.
Mistake: Expecting pop() to remove the first or last item.
Fix: Sets have no order, so pop removes an arbitrary item.
Mistake: Using b = a to copy a set.
Fix: Use b = a.copy() or set(a).

Important tips

  • Use discard when absence is not an error.
  • Use update with any iterable to add many items at once.
  • Use the method forms when one side is not a set.

Key points summary

  • add adds one item; update adds many.
  • remove raises KeyError; discard does not.
  • The algebra methods return new sets; the _update versions change in place and return None.
  • issubset, issuperset and isdisjoint return booleans.
  • copy gives an independent set.

Exam and interview points

  • remove raises KeyError for a missing item; discard does not.
  • update() returns None.
  • a.union(iterable) works with non-set arguments; a | list does not.
  • Sets have no index, so pop is arbitrary.

Quick revision

  • add one, update many.
  • remove strict, discard gentle.
  • union / intersection / difference / symmetric_difference.
  • issubset, issuperset, isdisjoint.

Frequently asked questions

What is the difference between update and union?

union returns a new set and leaves the original alone. update changes the original set and returns None.

Which item does pop remove?

An arbitrary one, which you cannot predict or choose. Do not depend on it.

Can add take a list?

No. A list is unhashable, so add([1, 2]) raises TypeError. Use update([1, 2]) or add a tuple.

Is the empty set a subset of every set?

Yes. There are no items in it that could be missing from the other set.

Practise this chapter

23 practice questions Take the chapter quiz

Related chapters