Explain it simply
Explain it simply
Picture checking a guest list at the door of an event. Aye walked in and out three times, but her name should appear on the list only once. You also want to answer "has this person arrived?" instantly, without reading the whole list from the top.
A Python set is exactly that kind of list. Adding a value twice still stores it once, and checking with in is very fast. The price you pay is order: a set does not remember what you added first, and you cannot fetch an element by index.
Problem → Why → Solution
The problem: deduplicating with a list
Users typed tags for a blog post, so "python" and "web" each appear twice. The first idea is to turn the list into a set and back into a list. The duplicates do disappear, but the tag order can change from one run of the program to the next, and the order the user typed is lost.
The second problem is speed. Using in on a list makes Python compare elements one by one from the front. Searching a list of a hundred thousand banned user IDs on every login wastes real time.
tags = ["python", "web", "python", "api", "web"]
unique_tags = list(set(tags))
print(unique_tags) # order may differ on every run!
print(unique_tags[0]) # "first" tag is now a coin toss
banned = list(range(100_000))
print(99_999 in banned) # scans the whole listWhy does this happen?
A set does not store values in the order you added them; it places them in a hash table based on each value's hash. String hashes are randomized per process for security, so the order can change between runs. That same hash table is why in is many times faster than on a list. When order matters, use an order-preserving approach such as list(dict.fromkeys(tags)).
Core concept: unique, unordered and hash-based
You create a set with curly braces, {"apple", "banana"}, or with set(iterable). set([1, 2, 2, 3]) becomes {1, 2, 3}: duplicates vanish automatically. An empty set must be written set(), because {} is an empty dictionary. Also note that set("hello") takes each character of the string as an element and gives {'h', 'e', 'l', 'o'}.
Internally, a set computes each element's hash and uses it to jump straight to a storage slot. That is why x in my_set takes about the same time on average however large the set is, while in on a list grows with the number of elements. The consequence of this design is that elements must be hashable: immutable values such as int, float, str and tuple are fine, but putting a list, dict or set inside raises TypeError: unhashable type: 'list'.
Sets are mutable. add(x) inserts one element and update(iterable) inserts many at once. To delete, remove(x) raises KeyError when x is missing, while discard(x) quietly does nothing. pop() removes and returns an arbitrary element, and clear() empties the set. Indexing is not possible: my_set[0] is a TypeError. len(my_set) counts the unique elements, and a for loop visits each element exactly once, in no guaranteed order.
Comparing two groups is where sets shine. a | b (union) gives every element from both, a & b (intersection) gives what both share, a - b (difference) gives what only a has, and a ^ b (symmetric difference) gives what exactly one side has. When you need a set that cannot change, use frozenset: it is hashable, so it can be a dict key or an element of another set.
- Compute the value's hash
- Jump straight to its slot
- Already there? Store nothing new
- No order kept, only membership
A value that cannot be hashed (a list, a dict) has no slot to go to, so it cannot enter a set.
General pattern
items = {value1, value2} # literal (never {} for empty)
empty = set() # empty set
from_list = set(iterable) # removes duplicates
items.add(value) # one element
items.update(iterable) # many elements
items.discard(value) # remove, no error if missing
value in items # fast membership test
a | b, a & b, a - b, a ^ b # union, intersection, difference, symmetricA literal and set() are the two ways to create one. add/update insert, discard (or remove) delete. in tests membership, and the four operators each build a new set from two sets.
Example: unique visitors and permission sets
The visit log repeats names. We use a set to count the real number of people, add and remove some, and then compare admin and editor permissions with the four operators. Notice that every set is passed through sorted() before printing, so the output is stable across runs.
visits = ["aye", "bo", "aye", "chit", "bo", "aye"]
visitors = set(visits)
print(len(visits), "visits from", len(visitors), "people")
print(sorted(visitors))
print("chit" in visitors, "dan" in visitors)
visitors.add("dan")
visitors.add("aye")
visitors.update(["ei", "bo"])
visitors.discard("zaw")
visitors.remove("chit")
print(sorted(visitors))
admin = {"read", "write", "delete"}
editor = {"read", "write", "publish"}
print("union: ", sorted(admin | editor))
print("intersection:", sorted(admin & editor))
print("difference: ", sorted(admin - editor))
print("symmetric: ", sorted(admin ^ editor))
empty = set()
print(type(empty).__name__, type({}).__name__)Code breakdown
- Line 2
visitors = set(visits)set() reads the list and keeps one copy of each repeated name, which is why six visits collapse into three people.
- Line 4
print(sorted(visitors))sorted() returns the set as an alphabetical list. Printing the set directly could show the strings in a different order on each run.
- Lines 8-12
visitors.discard("zaw")Adding "aye" again changes nothing, and update() inserts every name from a list in one call. "zaw" is not present, yet discard() raises no error; remove("chit") succeeds because chit is there.
- Lines 17-20
print("intersection:", sorted(admin & editor))& shows the permissions both roles share (read, write), - shows what only admin has (delete), and ^ shows what exactly one role has: delete and publish.
- Line 23
print(type(empty).__name__, type({}).__name__)Proves that set() is a set while {} is a dict.
6 visits from 3 people
['aye', 'bo', 'chit']
True False
['aye', 'bo', 'dan', 'ei']
union: ['delete', 'publish', 'read', 'write']
intersection: ['read', 'write']
difference: ['delete']
symmetric: ['delete', 'publish']
set dict
Subsets, supersets and the method versions
a <= b checks whether every element of a is also in b (a subset), and a >= b checks for a superset. a.isdisjoint(b) is True when the two share nothing at all. Each operator also has a method version (union, intersection, difference), and the methods accept any iterable: a.union([4, 5]) works, while a | [4, 5] is a TypeError.
required = {"read", "write"}
granted = {"read", "write", "delete"}
print(required <= granted) # True: every required permission is granted
print(granted.isdisjoint({"admin"})) # True: nothing in common
print(sorted(required.union(["publish"])))
print(frozenset({"read"}) in {frozenset({"read"}), frozenset({"write"})})In real projects
Where this shows up in real projects
Permission systems use sets constantly. To allow an action, code checks required <= granted, and it computes the missing permissions with required - granted to put them in the error message. When that message goes to a log or the UI, it is sorted first so tests and screenshots stay stable.
Sets are also everyday tools in data cleaning. Turn the email columns of two CSV files into sets, use intersection to find shared customers, and use difference to drop people who unsubscribed. A web crawler keeps a visited set of URLs so it never downloads the same page twice. Large lookup tables, such as banned words or blocked IP addresses, are stored as sets instead of lists so checking each request stays fast.
Common mistakes
Common mistakes
1. Writing {} for an empty set
seen = {} followed by seen.add("x") fails with AttributeError: 'dict' object has no attribute 'add', because empty curly braces make a dictionary. Always write an empty set as seen = set().
2. Trusting the order of a set
Treating list(set(tags))[0] as "the first tag", or comparing the printed text of a set of strings in a test, passes on one run and fails on the next. Use sorted() for display, or list(dict.fromkeys(items)) to deduplicate while keeping the original order.
3. Calling remove() on a value that may be missing
remove() stops the program with KeyError when the value is absent. If you mean "remove it if it is there", call discard(). Keep remove() for places where a missing value really is a bug you want to hear about.
4. Putting a list inside a set
{[1, 2], [3, 4]} raises TypeError: unhashable type: 'list'. Store pairs such as coordinates as tuples instead: {(1, 2), (3, 4)}.
Best practices
Best practices
- Convert a large list you will search repeatedly into a set once, before the loop starts.
- Sort a set every time you show it to a user or write it to a log.
- Define constant groups that must never change, such as VALID_ROLES, as a frozenset.
Mini challenge
Mini challenge: compare two course rosters
The Python course signup list contains repeated names. Use sets to remove duplicates and print a report comparing it with the SQL course.
- Turn the signup list into a set and print how many duplicates were removed
- Print, with sorted(), who takes both courses, Python only, and any course
- Check with in whether "nu" is in the Python course
- After add()-ing nu, check whether the SQL set is a subset of the Python set
signups = ["mya", "zaw", "mya", "hla", "zaw", "ko"]
sql_class = {"hla", "ko", "nu"}
# TODO: python_class = a set built from signups
# TODO: print how many duplicates were removed (compare two lengths)
# TODO: print sorted lists for: both courses, python only, any course
# TODO: print whether "nu" is in python_class
# TODO: add "nu" to python_class, then print whether sql_class is a subsetExpected: duplicates removed: 2 both courses: ['hla', 'ko'] python only: ['mya', 'zaw'] any course: ['hla', 'ko', 'mya', 'nu', 'zaw'] nu in python? False sql is a subset now? True
Show hint
The number of duplicates is len(signups) - len(python_class). For the subset check, use the <= operator or issubset().
Show solution
signups = ["mya", "zaw", "mya", "hla", "zaw", "ko"]
sql_class = {"hla", "ko", "nu"}
python_class = set(signups)
print("duplicates removed:", len(signups) - len(python_class))
print("both courses:", sorted(python_class & sql_class))
print("python only: ", sorted(python_class - sql_class))
print("any course: ", sorted(python_class | sql_class))
print("nu in python?", "nu" in python_class)
python_class.add("nu")
print("sql is a subset now?", sql_class <= python_class)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A set stores only unique values and has no order or index; write an empty set as set().
- It is built on a hash table, so in is fast and elements must be hashable (str, int, tuple).
- Insert with add/update; delete with remove (raises KeyError) or discard (never raises).
- Compare groups with |, &, - and ^, and sort the result whenever you display it.
The Python Tutorial — Python Software Foundation