Skip to content
Kuza Ndoto Academy

Sets

Beginner → IntermediateChapter 4 · Page 22 of 564 min readUpdated 15 Nov 2026

A set is an unordered collection of unique items. Sets automatically remove duplicates, check membership very quickly and support maths-style operations such as union and intersection. They're perfect for questions like "which students are in both clubs?"

Creating sets

Write items inside curly braces, or convert another collection with set(). Duplicates simply disappear.

rolls = [4, 2, 4, 1, 2, 4]
unique_rolls = set(rolls)

print(unique_rolls)
print(len(unique_rolls))
{1, 2, 4} 3
Common mistake

{} creates an empty dictionary, not an empty set. For an empty set, write set(). Python even displays an empty set as set().

a = {}
b = set()
print(type(a))
print(type(b))
print(b)
<class 'dict'> <class 'set'> set()

Sets have no order

A set doesn't keep items in the order you added them, so you can't use indexes: my_set[0] raises a TypeError. When you print a set of strings, the order can even change from one run of the program to the next. When order matters for display, wrap the set in sorted(), which returns a sorted list. The examples on this page do that so their output is predictable.

counties = {"Nakuru", "Kisumu", "Nakuru", "Mombasa", "Kisumu"}
print(sorted(counties))
print(len(counties))
['Kisumu', 'Mombasa', 'Nakuru'] 3

Adding and removing items

booked = {1, 3}
booked.add(5)
booked.add(3)          # already there: nothing happens
print(booked)

booked.discard(7)      # not there: no error
booked.remove(3)
print(booked)
{1, 3, 5} {1, 5}
  • add(x) inserts one item (ignored if it's already present).
  • update(iterable) adds several items at once.
  • remove(x) deletes an item and raises KeyError if it's missing.
  • discard(x) deletes an item if present and quietly does nothing otherwise.
Common mistake

Using remove() for an item that might not be there: booked.remove(7) stops the program with KeyError: 7. Use discard() when a missing item is fine.

Fast membership tests

Checking x in my_set is extremely fast, even for huge sets, because sets use a technique called hashing to jump straight to where an item would be. Checking x in my_list has to look through the items one by one. If you test membership often, for example checking registered phone numbers, a set is the right tool.

registered = {"0712345678", "0722000111", "0733444555"}
print("0722000111" in registered)
print("0799999999" in registered)
True False

Set operations

Sets support the operations you may know from maths. Each has an operator and an equivalent method.

OperationOperatorMethodResult contains…
Uniona | ba.union(b)items in either set
Intersectiona & ba.intersection(b)items in both sets
Differencea - ba.difference(b)items in a but not in b
Symmetric differencea ^ ba.symmetric_difference(b)items in exactly one of the sets
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)
print(a & b)
print(a - b)
print(b - a)
print(a ^ b)
{1, 2, 3, 4, 5, 6} {3, 4} {1, 2} {5, 6} {1, 2, 5, 6}
a b 1 2 3 4 5 6 a - b = {1, 2} a & b = {3, 4} b - a = {5, 6}
Figure 1. The overlap is the intersection a & b. Everything inside either circle is the union a | b, and the two outer parts together are the symmetric difference a ^ b = {1, 2, 5, 6}.

Here's a more realistic use, comparing members of two school clubs:

football = {"Achieng", "Brian", "Chebet"}
drama = {"Brian", "Dalia", "Chebet"}

print("Both clubs:", sorted(football & drama))
print("Any club:", sorted(football | drama))
print("Football only:", sorted(football - drama))
Both clubs: ['Brian', 'Chebet'] Any club: ['Achieng', 'Brian', 'Chebet', 'Dalia'] Football only: ['Achieng']

You can also test relationships: {1, 2} <= {1, 2, 3} (or .issubset()) is True because every item on the left is in the right-hand set.

What can go in a set?

Set items must be hashable, which in practice means immutable: numbers, strings, Booleans and tuples of these. Lists, dictionaries and other sets can't be set items; {[1, 2]} raises a TypeError saying the list is unhashable. If you need a set that can't change, and can itself go inside another set, use frozenset().

Tip

To remove duplicates from a list, list(set(items)) works but loses the original order. To keep the order, use list(dict.fromkeys(items)), which relies on dictionaries remembering insertion order.

Key points

  • Sets store unique, unordered items; duplicates are dropped automatically.
  • Use set() for an empty set, because {} is an empty dictionary.
  • add(), discard() and remove() change a set; remove() fails on missing items.
  • |, &, - and ^ give union, intersection, difference and symmetric difference.
  • Membership tests on sets are very fast; items must be immutable.
Up next · Data StructuresDictionariesStore data as key–value pairs.
→

Tip: use the ← and → keys to move between pages.