A set holds each item at most once and answers “is this item present?” very quickly. Sets are used to remove duplicates, test membership and perform the mathematical set operations you know from discrete mathematics.
What a set is
Unordered: no indexing or slicing; the display order is not meaningful and can differ between runs.
Unique: duplicates are removed automatically.
Mutable: items can be added and removed (but the items themselves must be hashable).
An empty set is set(); {} creates an empty dictionary.
Set operations
With a = set('abrakadabra') = {a, b, d, k, r} and b = set('alexander') = {a, d, e, l, n, r, x}:
Operation
Operator
Method
Result
Union (in either)
a | b
a.union(b)
{a, b, d, e, k, l, n, r, x}
Intersection (in both)
a & b
a.intersection(b)
{a, d, r}
Difference (in a only)
a - b
a.difference(b)
{b, k}
Symmetric difference (in exactly one)
a ^ b
a.symmetric_difference(b)
{b, e, k, l, n, x}
Subset / superset
a <= b, a >= b
issubset, issuperset
Disjoint (nothing in common)
a.isdisjoint(b)
False
A ∪ Beverything in A or B or both
A ∩ Bonly what is in both
A − Bin A but not in B
A △ Bin exactly one of them
The four set operations on A and B
Changing a set
Method
Effect
add(x)
Add one item
update(iterable)
Add many items
remove(x)
Remove x; KeyError if absent
discard(x)
Remove x if present; no error otherwise
pop()
Remove and return an arbitrary item
clear()
Remove all items
copy()
Shallow copy
Frozensets
A frozenset is an immutable set: it supports all the non-changing operations (union, intersection, membership) but no add, remove or update. Because it is hashable, it can be an item of another set or a dictionary key.
Key takeaways
Sets hold unique hashable items, unordered, with fast in tests.
add, update, remove, discard, pop, clear change a set.
frozenset is immutable and can be a key or a set item.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Two lists hold the email addresses of users who visited a website on Monday and on Tuesday. Write statements that find the users who visited on both days, on Monday only, and the total number of different users.
Show worked answer
mon = set(monday_list), tue = set(tuesday_list). Both days: both = mon & tue. Monday only: mon_only = mon - tue. Total different users: len(mon | tue). Converting to sets removes repeated visits by the same user, and the set operators answer each question in one expression.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-structures-and-control-statements-in-python/sets-and-frozensets/ to read this page.