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.
Before this lesson: Python Lists, Python Tuples
2Python Sets: diagram
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.
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_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 themEach 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
- Python List vs Set: Differences and When to Use Each — A **list** keeps items in order and allows duplicates, while a **set** stores only unique items with no index…
- How to Remove Duplicates from a List in Python — Use `list(dict.fromkeys(items))` to remove duplicates **and keep the original order**. Use `list(set(items))`…
- Python Program to Find the Second Largest Number in a List — To find the second largest number, remove duplicates, sort, and take the second from the end: `sorted(set(num…
- Python Set add() Method — `set.add(element)` inserts **one** element into a set in place and returns `None`. If the element is already …
- Python Set remove() Method — `set.remove(element)` deletes the element from the set in place and returns `None`. If the element is **not**…
- Python Dictionary keys() Method — `dict.keys()` returns a live, read-only view of all the keys in a dictionary, in insertion order. Convert it …
- Python Set discard() Method — `set.discard(element)` removes the element from the set if it is present and does nothing if it is not. It al…
- Python Set pop() Method — `set.pop()` removes one **arbitrary** element from the set and returns it. On an empty set it raises `KeyErro…
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.
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.
- Line 1-2The list has six tags, some repeated.
set(tags)keeps one copy of each, leaving four. - Line 3Comparing
len()of the list and the set shows how many repeats were removed. - Line 4
sorted()turns the set into an alphabetical list, so the output is the same every time. - Line 6-8Adding
"python"changes nothing because it is already there;"testing"is new, so the size goes from 4 to 5. - Line 10-11
inchecks membership. For a set, this lookup is fast no matter how many tags there are. - Line 13A second set is written directly with curly braces.
- Line 14
&(intersection) keeps the tags found in both sets. - Line 15
-(difference) keeps the tags inunique_tagsthat are not inbeginner. - Line 16
|(union) combines both sets, still without duplicates.
8Python Sets: common mistakes
Using {} to create an empty set
✗ Wrong
seen = {}
seen.add(5)✓ 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])✓ 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)))✓ 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 ✓ Completedvisitor_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.
visitor_ids = [101, 205, 101, 330, 205, 101, 412]
unique_count = 0
# your code here
visitor_ids = [101, 205, 101, 330, 205, 101, 412]
unique_count = len(set(visitor_ids))
print(unique_count)
2. Predict the set operations
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
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)){3, 4}
[1, 2]
5
4
2 more exercises → 4 more examples
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