Python Sets
Beginner Data Structures

Python Sets

1Python Sets: overview

A set is an unordered collection of unique values: adding a value that is already there changes nothing, and checking whether a value is in the set is very fast.

GoalBy the end you can create sets, remove duplicates from a list, add and remove items, test membership, and combine sets with union, intersection and difference.

Before this lesson: Python Lists, Python Tuples

2Python Sets: diagram

Python Setslist: visits[7, 3, 7, 5, 3, 7]6 items, repeats keptset: unique visitors{3, 5, 7}3 items, no orderset(visits)
Turning a list into a set keeps one copy of each value and drops the repeats. The set does not remember the original order or positions.

3Python Sets: explained step by step

A set stores each value at most once. You create one with curly braces, or by passing any collection to set():

primes = {2, 3, 5, 7}
letters = set("banana")     # three letters: a, b and n
empty = set()               # not {} - that makes an empty dictionary

Duplicates disappear

Adding a value that is already in a set does nothing, so converting a list to a set is the quickest way to remove repeats. len() then tells you how many different values there were.

Python
visits = [7, 3, 7, 5, 3, 7]
unique = set(visits)
print(unique)
print(len(visits), "visits from", len(unique), "visitors")

No order, no positions

A set doesn't keep items in the order you added them, and it has no indexes, so my_set[0] is an error. For sets of strings, the display order can even change from one run to the next. When you need a predictable order, use sorted(my_set), which returns a sorted list. The examples in this lesson do that whenever they print strings.

Changing a set

Sets are mutable. add(x) puts in one value and update(items) adds several. remove(x) deletes a value but raises a KeyError if it is missing, while discard(x) quietly does nothing in that case.

Fast membership tests

x in my_set is answered almost instantly, however large the set is. A list has to compare x with its items one by one; a set uses each value's hash (a number calculated from the value) to jump straight to the right place. If your program asks "have I seen this before?" many times, a set is the right tool. This is also why set items must be immutable values such as numbers, strings and tuples: a list can't go inside a set.

Combining sets

Sets support the operations you may know from Venn diagrams:

Python
python_club = {1, 2, 3, 4}
chess_club = {3, 4, 5}
print(python_club | chess_club)   # union: in either club
print(python_club & chess_club)   # intersection: in both
print(python_club - chess_club)   # difference: only in python_club
print(python_club ^ chess_club)   # in exactly one of them

Each operator also has a method: union(), intersection(), difference() and symmetric_difference(). The methods accept any iterable, so python_club.union([8, 9]) works with a list too. You can also ask whether one set is completely inside another with a <= b (or a.issubset(b)).

Quick reference: Python Sets

4Python Sets: syntax

s = {item1, item2}         # set literal
s = set(iterable)          # from a list, string, ...
empty = set()              # {} is an empty dict!
s.add(x)    s.update(items)
s.discard(x)               # remove if present
s.remove(x)                # KeyError if missing
x in s                     # fast membership test
a | b    a & b    a - b    a ^ b
sorted(s)                  # a sorted list: predictable order

5Python Sets: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
tags = ["python", "web", "python", "data", "web", "api"]
unique_tags = set(tags)
print("Tags used:", len(tags), "| unique:", len(unique_tags))
print("Sorted:", sorted(unique_tags))

unique_tags.add("python")
unique_tags.add("testing")
print("After adding:", len(unique_tags))

if "data" in unique_tags:
    print("Has a data tag")

beginner = {"python", "web", "html"}
print("Both:", sorted(unique_tags & beginner))
print("Only in tags:", sorted(unique_tags - beginner))
print("Either:", sorted(unique_tags | beginner))
Expected outputTags used: 6 | unique: 4
Sorted: ['api', 'data', 'python', 'web']
After adding: 5
Has a data tag
Both: ['python', 'web']
Only in tags: ['api', 'data', 'testing']
Either: ['api', 'data', 'html', 'python', 'testing', 'web']

7Python Sets: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1-2The list has six tags, some repeated. set(tags) keeps one copy of each, leaving four.
  2. Line 3Comparing len() of the list and the set shows how many repeats were removed.
  3. Line 4sorted() turns the set into an alphabetical list, so the output is the same every time.
  4. Line 6-8Adding "python" changes nothing because it is already there; "testing" is new, so the size goes from 4 to 5.
  5. Line 10-11in checks membership. For a set, this lookup is fast no matter how many tags there are.
  6. Line 13A second set is written directly with curly braces.
  7. Line 14& (intersection) keeps the tags found in both sets.
  8. Line 15- (difference) keeps the tags in unique_tags that are not in beginner.
  9. Line 16| (union) combines both sets, still without duplicates.

8Python Sets: common mistakes

Using {} to create an empty set

✗ Wrong

seen = {}
seen.add(5)
AttributeError: 'dict' object has no attribute 'add'

✓ Right

seen = set()
seen.add(5)
print(seen)

Empty curly braces create an empty dictionary. Use set() for an empty set.

Reading a set by index

✗ Wrong

colors = {"red", "green", "blue"}
print(colors[0])
TypeError: 'set' object is not subscriptable

✓ Right

colors = {"red", "green", "blue"}
first = sorted(colors)[0]
print(first)

Sets have no positions. Use in to test for a value, loop over the set, or turn it into a sorted list first.

Expecting a set to keep the original order

✗ Wrong

steps = ["wash", "cut", "wash", "cook"]
print(list(set(steps)))
The steps come out in an unpredictable order, e.g. ['cut', 'cook', 'wash']

✓ Right

steps = ["wash", "cut", "wash", "cook"]
seen = set()
ordered = []
for step in steps:
    if step not in seen:
        seen.add(step)
        ordered.append(step)
print(ordered)

A set forgets order. To remove repeats but keep the first-seen order, loop over the list and use a set only to remember what you've already seen.

9Python Sets: exercises

Write your answer, then press Check. The checks run in your browser.

1. Count unique visitors

Write code Easy

visitor_ids contains one ID per page visit, so the same visitor can appear several times. Store the number of different visitors in unique_count and print it.

Your code
visitor_ids = [101, 205, 101, 330, 205, 101, 412]
unique_count = 0

# your code here

2. Predict the set operations

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a & b)
print(sorted(a - b))
print(len(a | b))
a.add(2)
print(len(a))

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why does my set print in a different order each time?

Sets are unordered. For strings, Python randomises the hash values each time a program starts, so the display order can change between runs. Use sorted(my_set) whenever you need a predictable order.

Why can't I put a list inside a set?

Set items must be hashable, which means immutable. A list can change, so Python raises TypeError: unhashable type: 'list'. Convert it to a tuple first if you need to store it in a set.

Should I check membership with a list or a set?

If you check only once or twice, either is fine. If you check many times, or the collection is large, convert it to a set first: x in my_set stays fast as the set grows, while a list gets slower.

Further reading

10Next lesson

Up nextPython Set OperationsSet operations answer questions about whole groups in one step: union, intersection, difference and symmetric differenc…

Related:
Python ListsPython TuplesPython Set OperationsPython Dictionaries

← Python Sorting · All Data Structures lessons · Practise in the IDE