PythonMastery
reference 5 min read · lesson 5 of 25 in Reference

Python Set Operations Cheat Sheet

1 · The lesson

read

A set holds each value only once, in no fixed order. Use a set to remove duplicates, to check very fast whether a value is present, and to compare two groups of values: what they share, and what only one of them has. For the full tutorial, see Sets.


1. Create a set

Curly brackets with values inside make a set. Empty curly brackets {} make an empty dict, so write set() for an empty set.

python
{3, 1, 3}                     # {1, 3}  (the duplicate is removed)
set()                         # set()  (the only way to write an empty set)
set([1, 2, 2, 3])             # {1, 2, 3}  (anything you can loop over becomes a set)
sorted(set("hello"))          # ['e', 'h', 'l', 'o']  (sorted() gives a predictable order)
{n % 3 for n in range(10)}    # {0, 1, 2}  (a set comprehension: a set built from a loop)
frozenset([1, 2])             # frozenset({1, 2})  (a set that cannot change)
type({})                      # <class 'dict'>

2. Add and remove

MethodWhat it does
s.add(x)Adds one item. Nothing happens if it is already there
s.update(items)Adds each item of a list, set or other collection
s.discard(x)Removes x if it is there. No error if it is not
s.remove(x)Removes x. Raises KeyError if it is not there
s.pop()Removes one item and returns it (you cannot choose which)
s.clear()Removes everything
python
s = {1, 2}
s.add(3)            # {1, 2, 3}
s.update([4, 5])    # {1, 2, 3, 4, 5}
s.discard(9)        # {1, 2, 3, 4, 5}  (9 was not there: no error)
s.remove(5)         # {1, 2, 3, 4}

3. Check membership

x in s is very fast for a set: it takes about the same time with 10 million items as with 10. For a list, Python must check the items one by one. If you check a list many times, turn it into a set first.

python
banned = {"spam", "eggs"}
words = ["ham", "spam", "jam", "ham"]
"spam" in banned                          # True
"ham" not in banned                       # True
[w for w in words if w not in banned]     # ['ham', 'jam', 'ham']  (keeps the words that are not banned)
len(set(words))                           # 3  (the number of different words)
banned.isdisjoint(words)                  # False  (False means at least one word is banned)

4. Combine two sets

OperatorMethodGives you
a \| ba.union(b)the union: items in either set
a & ba.intersection(b)the intersection: items in both sets
a - ba.difference(b)the difference: items in a but not in b
a ^ ba.symmetric_difference(b)items in exactly one of the sets
python
a, b = {1, 2, 3}, {2, 3, 4}
a | b                        # {1, 2, 3, 4}
a & b                        # {2, 3}
a - b                        # {1}
b - a                        # {4}  (the order matters for -)
a ^ b                        # {1, 4}
a.union([4, 5])              # {1, 2, 3, 4, 5}  (a method also accepts a list)
a.intersection(b, {3, 9})    # {3}  (a method can take several sets at once)
groups = [{1, 2}, {2, 3}, {2, 4}]
set.intersection(*groups)    # {2}  (the items that every set in the list shares)

The operators need a set on both sides, so {1, 2} | [3] raises a TypeError. The methods accept a list as well.

5. Update a set in place

Each operator has a version with = that changes the set on the left instead of building a new one.

python
a, b = {1, 2, 3}, {2, 3, 4}
a |= b              # {1, 2, 3, 4}  (the same as a.update(b))
a &= {2, 3, 9}      # {2, 3}  (keeps only the items that are also in {2, 3, 9})
a -= {3}            # {2}  (removes 3 from a)
b ^= {4, 7}         # {2, 3, 7}  (removes the shared 4, adds the new 7)

6. Compare sets

A set is a subset of another set when all its items are also in the other set. A superset is the opposite: it contains every item of the other set.

python
{1, 2} <= {1, 2, 3}             # True  (a subset; the method is issubset())
{1, 2} < {1, 2}                 # False  (< also needs the left set to be smaller)
{1, 2, 3} >= {3}                # True  (a superset; the method is issuperset())
{1, 2}.issubset([1, 2, 5])      # True  (the method accepts a list)
{1, 2} == {2, 1}                # True  (the order of the items never matters)
{1, 2}.isdisjoint({3, 4})       # True  (the two sets have no items in common)

7. Loop and summarise

A set has no fixed order. Loop over sorted(s) when you want the same order every time.

python
a = {3, 1, 2}
for x in sorted(a):
    print(x)
len(a)                        # 3
min(a), max(a), sum(a)        # (1, 3, 6)
sorted(a, reverse=True)       # [3, 2, 1]  (sorted() always returns a list)
python
1
2
3

8. frozenset

A normal set can change, so it cannot be a dict key or an item in another set. A frozenset cannot change, so it can be a dict key or an item in a set. Use it as a key when the order of the items does not matter, such as a pair of people.

python
teams = {frozenset({"Ada", "Grace"}): "A"}
teams[frozenset({"Grace", "Ada"})]          # 'A'  (the order inside does not matter)
frozenset({1, 2}) | {3}                     # frozenset({1, 2, 3})
{frozenset({1, 2}), frozenset({2, 1})}      # {frozenset({1, 2})}

9. Useful patterns

python
xs, ys = [3, 1, 3, 2], [2, 3, 5]
sorted(set(xs))                  # [1, 2, 3]  (each different value once, sorted)
list(dict.fromkeys(xs))          # [3, 1, 2]  (removes repeats and keeps the original order)
len(xs) == len(set(xs))          # False  (True only if no item repeats)
set(xs) & set(ys)                # {2, 3}  (items in both lists)
set(ys) - set(xs)                # {5}  (items only in ys)
set(xs) | set(ys)                # {1, 2, 3, 5}  (every item from both lists, once each)
max(set(xs), key=xs.count)       # 3  (the most common value)
{w.lower() for w in ["Hi", "hi", "HI"]}    # {'hi'}  (each word once, ignoring case)

Common mistakes

Writing {} for an empty set. {} is an empty dict. Write set().

Putting a list in a set. An item must be hashable: a value that cannot change, such as a number, a string or a tuple. {[1, 2]} raises TypeError: unhashable type: 'list' (full error page). Use a tuple: {(1, 2)}.

Expecting set("hello") to hold the word. set() loops over the string and stores each letter. Curly brackets store the whole word:

python
len(set("hello"))     # 4  (h, e, l, o)
len({"hello"})        # 1

Indexing a set. A set has no order, so s[0] raises TypeError: 'set' object is not subscriptable. Write sorted(s)[0].

Using an operator with a list. {1, 2} | [3] raises TypeError. Write {1, 2}.union([3]) or {1, 2} | set([3]).

Values that are equal count once. 1, 1.0 and True are equal in Python:

python
{1, True, 1.0}        # {1}

Removing duplicates with list(set(xs)) and expecting the order to stay. A set does not keep the order. Use list(dict.fromkeys(xs)) when the order matters.

Changing a frozenset. frozenset({1}).add(2) raises AttributeError: 'frozenset' object has no attribute 'add'. Use a normal set if you need to change it.

Assigning the result of add(). add() changes the set and returns None, so s = s.add(4) replaces your set with None. Write s.add(4) on its own.

See also

Practice this

on practicepython.in

Short exercises that run in your browser and tell you what your code did, as well as whether a test passed.

Found this useful? Share it with a friend who’s learning Python.