Python Sets · Lesson 59 of 149

Python Sets

What you will learn

  • What a set is: unique items with no order
  • How to create one, and why {} is not an empty set
  • Adding and removing items
  • Membership tests and removing duplicates
  • Set comprehensions
  • The errors and rules for what a set can hold

1. What is a set?

A set (type set) is a collection of unique items with no order and no positions. It is written with curly brackets, like a dictionary, but with single items and no colons:

s = {3, 1, 2, 3, 1}
print(sorted(s), len(s), type(s))
[1, 2, 3] 3 <class 'set'>

The repeated 3 and 1 were stored once. Sets are used when you care about which items are there, not about how many times or in what order: the different words in a text, the guests who have arrived, the customers who bought something.

A set is mutable (items can be added and removed), but the items inside it must be hashable, which means immutable: numbers, text, tuples of those (lesson 9.7).

Quick check: how many items does `{1, 1, 2, 2, 2}` hold?

2: the items 1 and 2. Repeats are dropped.

2. Creating sets

print(set())
print(set([1, 2, 2]))
print(sorted(set("hello")))
print(set(range(3)))
print(sorted(set({"a": 1, "b": 2})))
set()
{1, 2}
['e', 'h', 'l', 'o']
{0, 1, 2}
['a', 'b']
  • set(collection) makes a set from any collection, dropping repeats. A string gives its distinct characters, and a dictionary gives its keys.
  • set() with nothing inside is the empty set.

The empty-set trap

{} makes an empty dictionary, not an empty set:

print(type({}), type(set()))
<class 'dict'> <class 'set'>

The reason is history: dictionaries used the empty curly brackets first. For an empty set, you must write set().

3. No order, no index

A set has no positions, so you cannot read or assign by index:

s = {3, 1, 2}
s[0]
TypeError: 'set' object is not subscriptable

The order in which a set shows its items is an internal detail and may change from run to run, especially for text (lesson 9.7). For example, list({100, 5, 17, 3}) gave [17, 3, 100, 5] on the test computer. So:

  • Never depend on the order of a set.
  • To see it in a fixed order, use sorted(s), which gives a list.

4. Adding and removing

Method What it does
s.add(x) adds x (nothing happens if it is already there)
s.update(items) adds every item of a collection (or several)
s.remove(x) removes x; KeyError if it is missing
s.discard(x) removes x if present; no error if missing
s.pop() removes and returns an arbitrary item; KeyError if empty
s.clear() removes everything
s.copy() a shallow copy
s = {1, 2, 3}
s.add(10)
s.add(2)
s.update([20, 30])
print(sorted(s))

s.remove(2)
s.discard(99)
print(sorted(s))
[1, 2, 3, 10, 20, 30]
[1, 3, 10, 20, 30]

Adding 2 again changed nothing. remove(99) would raise KeyError: 99, while discard(99) quietly did nothing. Like the list and dictionary methods, add and update return None.

u = {5}
print(u.pop())
print(u)
u.pop()
5
set()
KeyError: 'pop from an empty set'

pop() takes an arbitrary item, because there is no "last". It is handy for emptying a set one item at a time.

5. Membership

Testing whether an item is in a set is very fast, however large the set (lessons 7.7 and 9.7):

s = {1, 3, 10}
print(3 in s, 9 in s, 9 not in s)
print(len(s), min(s), max(s), sum(s))
True False True
3 1 10 14

len, min, max, sum and sorted work as for other collections. This speed is the main reason to choose a set (lesson 10.3).

6. Removing duplicates

The best-known use of a set is to remove duplicates:

data = [3, 1, 3, 2, 1]
print(len(data), len(set(data)))
print(sorted(set(data)))
5 3
[1, 2, 3]

len(set(data)) counts the distinct values. Converting to a set loses the order, though. To remove duplicates and keep the order of first appearance, use a dictionary (lesson 9.5), or a loop with a seen set:

print(list(dict.fromkeys(data)))

seen = set()
out = []
for x in data:
    if x not in seen:
        seen.add(x)
        out.append(x)
print(out)
[3, 1, 2]
[3, 1, 2]

7. Equality and truth

Two sets are equal when they hold the same items, whatever the order. A set is never equal to a list:

print({1, 2} == {2, 1}, {1, 2} == [1, 2])
print(bool(set()), bool({0}))
True False
False True

An empty set is false and any other set is true (lesson 5.3). Items that are equal count as the same item, so {1, 1.0, True} holds just 1, and "a" and "A" are different.

8. Set comprehensions

Like lists and dictionaries, sets can be built with a comprehension: {expression for item in collection if condition} (chapter 12):

print(sorted({x * x for x in range(5)}))
print(sorted({n for n in range(10) if n % 3 == 0}))
print(sorted({c.upper() for c in "hello"}))
[0, 1, 4, 9, 16]
[0, 3, 6, 9]
['E', 'H', 'L', 'O']

Because the result is a set, repeats such as the two l letters appear once.

9. Errors and rules

Only hashable items can go in a set:

{[1], 2}
TypeError: unhashable type: 'list'

The same error appears for a set of sets or dictionaries ({{1}, 2}). Use tuples for items made of several values, and frozenset for a set inside a set (lesson 10.4).

You also cannot change a set's size while looping over it:

t = {1, 2, 3}
for x in t:
    t.add(x + 100)
RuntimeError: Set changed size during iteration

Loop over list(t) or sorted(t) if you need to change the set inside the loop (lesson 9.2 explained the same rule for dictionaries).

Worked example: who came and who is new?

Two days of visitors are recorded as lists, with repeats because some people entered more than once.

day1 = ["Rina", "Sam", "Lee", "Rina", "Mia"]
day2 = ["Sam", "Tom", "Mia", "Tom"]

visitors1 = set(day1)
visitors2 = set(day2)
print(len(day1), len(visitors1))
print(sorted(visitors1))
print(sorted(visitors2))
print("Lee" in visitors2, "Tom" in visitors1)
5 4
['Lee', 'Mia', 'Rina', 'Sam']
['Mia', 'Sam', 'Tom']
False False
Step What it shows
set(day1) Rina appeared twice but counts once: 5 entries, 4 people
sorted(...) a fixed order for printing
"Lee" in visitors2 False: Lee did not return

Lesson 10.2 shows how to ask "who came on both days?" in one expression. The names are made up.

Common mistakes

  • Writing {} for an empty set. It is a dictionary; write set().
  • Expecting an order, or indexing a set (s[0]).
  • Using remove for an item that may be missing. Use discard.
  • Putting a list or another set inside a set. Use a tuple or frozenset.
  • Changing a set's size while looping over it.
  • Using a set to remove duplicates and then expecting the old order.

Key takeaways

  • A set holds unique, hashable items with no order and no index.
  • Create one with {1, 2} or set(collection); the empty set is set(), not {}.
  • add, update, remove (error if missing), discard (no error), pop (arbitrary) and clear change a set.
  • x in s is fast; set(data) removes duplicates and loses the order; sorted(s) shows a set in order.
  • Equality ignores order; set comprehensions build sets in one line.

Practice

1. What is len({1, 2, 2, 3, 3, 3})?

Show answer

3: the distinct items are 1, 2 and 3.

2. How do you make an empty set?

Show answer

set(). The expression {} makes an empty dictionary.

3. What is the difference between s.remove(5) and s.discard(5) when 5 is not in s?

Show answer

remove raises a KeyError, and discard does nothing.

4. Count the different letters in "banana".

Show answer

len(set("banana")) gives 3 (the letters a, b and n).

5. Remove duplicates from ["b", "a", "b", "c", "a"] and keep the first-seen order.

Show answer

list(dict.fromkeys(["b", "a", "b", "c", "a"])) gives ['b', 'a', 'c'].

6. Why does {[1, 2], 3} fail?

Show answer

A list is mutable and unhashable, so it cannot be an item of a set. Use a tuple, {(1, 2), 3}.