Chapter 08
Python Sets
3 topics · 1 sections · beginner-friendly study notes · Updated
A set is an unordered collection of unique items.
You will learn creation, mathematical set operations, the set methods, and how a set differs from a dictionary.
Sets give very fast membership tests and automatic duplicate removal.
Unique visitors, removing duplicates, finding common friends, tag filtering.
Python Sets
A set is an unordered, mutable collection of UNIQUE, hashable items written inside curly braces, e.g. {1, 2, 3}. Duplicates are removed automatically and items have no index.
In short: A set is a bag of distinct things. Putting the same thing in twice keeps just one.
Think about it
Many problems become simple when you can ask "is it present?" or "what is common?" in one operation. Two students list their hobbies; the intersection shows common hobbies.
Create with {1, 2, 3} or `set(iterable)`.
An EMPTY set must be set() because {} creates an empty dictionary.
Items must be hashable (numbers, strings, tuples), so a list or another set cannot be inside a set.
Because there is no order, indexing and slicing are not allowed and the printed order may vary.
Membership x in s is O(1) on average, much faster than in a list.
Mathematical operators: | union, & intersection, - difference, ^ symmetric difference, <= subset, >= superset.
A frozenset is an immutable set that can itself be a set item or dict key.
Set comprehension: {x % 3 for x in range(10)}.
Note that 1, 1.0 and True count as the same element.
Key points
Example
CodeSet creation and set operators:
s = {3, 1, 2, 3, 1}
print(s) # {1, 2, 3} (duplicates removed)
empty_set = set() # NOT {}
empty_dict = {}
print(type(empty_set), type(empty_dict)) # set dict
print(set([1, 2, 2, 3])) # {1, 2, 3}
print(set("hello")) # {'h', 'e', 'l', 'o'} (order may vary)
print(list(set([3, 3, 1, 2]))) # remove duplicates from a list
print(2 in s, 9 in s) # True False
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3, 4}
print(a - b) # {1, 2}
print(a ^ b) # {1, 2, 5}
print({1, 2} <= a) # True (subset)
# s[0] # TypeError: sets are not indexable
# {[1, 2]} # TypeError: unhashable type: 'list'
evens_mod = {x % 3 for x in range(10)}
print(evens_mod) # {0, 1, 2}
fs = frozenset([1, 2])
print({fs: "ok"}) # frozenset can be a dict keyPython Set Methods
Set methods add, remove, combine and compare sets. Key ones are add, update, remove, discard, pop, clear, union, intersection, difference, symmetric_difference, issubset, issuperset, isdisjoint and copy.
In short: They are the named versions of the set operators plus tools to add and delete members.
Think about it
Output prediction and remove vs discard are classic exam points. Removing blocked users from a list of members using difference().
Adding: add(x) one item, `update(iterable)` many items.
Removing: remove(x) raises KeyError if missing, discard(x) does nothing if missing, pop() removes an ARBITRARY item, clear() empties the set.
Combining (return a NEW set): union, intersection, `difference, symmetric_difference`.
The in-place forms update, intersection_update, `difference_update and symmetric_difference_update` change the original set.
Comparison
issubset, issuperset, isdisjoint return booleans.
Methods accept any iterable (a list works), while operators need both sides to be sets.
copy() makes a shallow copy.
A frequent mistake: `s.
add([1, 2])` fails because a list is unhashable; use a tuple.
Key points
- remove vs discard: remove raises KeyError if absent; discard stays silent.
- Symmetric difference: Items in either set but not in both.
- isdisjoint:
Truewhen two sets share no items.
Read more
Example
CodeSet methods:
s = {1, 2}
s.add(3)
s.update([3, 4, 5])
print(s) # {1, 2, 3, 4, 5}
s.remove(5)
s.discard(99) # no error
# s.remove(99) # KeyError
print(s.pop() in {1, 2, 3, 4}) # True (arbitrary item removed)
a = {1, 2, 3}
b = {3, 4}
print(a.union(b)) # {1, 2, 3, 4}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
print(a.symmetric_difference(b)) # {1, 2, 4}
print(a.union([7, 8])) # methods accept any iterable
print({1}.issubset(a), a.issuperset({1, 2}), a.isdisjoint({9})) # True True True
a.intersection_update(b) # in place
print(a) # {3}
t = {1, 2}.copy()
t.clear()
print(t) # set()
# s.add([1, 2]) # TypeError: use a tuple instead
s.add((1, 2))add / update
Insert one item or many items.
remove / discard / pop / clear
Delete one item (strict or safe), an arbitrary item, or everything.
union / intersection / difference
Return new sets using set algebra.
issubset / issuperset / isdisjoint
Return True or False for relationships between sets.
Difference between Set and Dictionary in Python
A set stores unique items only and is written {1, 2}; a dictionary stores key-value pairs and is written {"a": 1}. Both use curly braces and both need hashable keys/items, but a set has no values.
In short: A set is a list of unique names. A dictionary is a phone book: a name (key) with a number (value).
Think about it
The shared braces confuse beginners, so this comparison is a common viva question. Set: unique roll numbers present today. Dictionary: roll number to student name.
Elements: set holds single items, dict holds key:value pairs.
Empty: set() versus {}.
Order: dictionaries keep insertion order (Python 3.7+), sets do not guarantee any order.
Access: dict d[key] returns the value; sets cannot be accessed by index or key, only tested with in.
Duplicates: set drops duplicate items; dict keeps one value per key (a repeated key overwrites).
Operators: sets support | & - ^; dicts support | merge (3.9+) but no intersection.
Both offer O(1) average lookup.
Choose a set to ask "is it there?
" and a dict to ask "what is associated with it?
".
Key points
- Key: Unique hashable label used to look up a value in a dictionary.
- Value: Data stored against a key; sets have none.
Read more
Example
CodeSet vs dictionary:
s = {1, 2, 3} # set
d = {1: "one", 2: "two"} # dictionary
print(type(s), type(d)) # set dict
print(2 in s, 2 in d) # True True (dict checks keys)
print(d[2]) # two
# print(s[2]) # TypeError: set is not subscriptable
d2 = {"a": 1, "a": 2}
print(d2) # {'a': 2} (later value wins)
print({1, 1, 2}) # {1, 2}
print({1, 2} | {2, 3}) # {1, 2, 3}
print({"a": 1} | {"b": 2}) # {'a': 1, 'b': 2} (Python 3.9+)
print(type({}), type(set())) # dict setSolved examples
Remove duplicates from [4, 2, 4, 1, 2] and show the sorted unique values.
Sorted unique list
Formula Applied:—Approach note: Converting to a set loses the original order.
Two clubs: A = {"ann", "raj", "li"} and B = {"raj", "sam"}. Find members in both and members in only A.
Two sets
Formula Applied:—Approach note: Difference is not symmetric: A - B differs from B - A.
What is type({})?
Type name
Formula Applied:—Approach note: Memorise: {} is a dict.
Given nums = [1, 2, 2, 3, 3, 3, 4], print the count of unique values using a set.
Unique count
Formula Applied:—Approach note: len(set(seq)) is the classic unique-count one-liner.
Real-world applications
Using Python Sets in real projects
Unique visitors, removing duplicates, finding common friends, tag filtering.
Common mistakes
❌ Myth: {} creates an empty set.
Why this is wrong: It creates an empty dictionary.
✅ Verified Truth: Use set().
⚠️ Exam Tip: A guaranteed MCQ.
❌ Myth: Sets keep insertion order.
Why this is wrong: Sets are unordered.
✅ Verified Truth: Dictionaries keep insertion order, sets do not.
⚠️ Exam Tip: Never rely on set order.
❌ Myth: A set can contain lists.
Why this is wrong: Lists are mutable and unhashable.
✅ Verified Truth: Store tuples or frozensets instead.
⚠️ Exam Tip: Remember the hashable rule.
Revision notes
A set is an unordered collection of unique items. You will learn creation, mathematical set operations, the set methods, and how a set differs from a dictionary.
High-Yield Quick Revision Points
- Set = unique, unordered, mutable, hashable items
- Empty set is set(), {} is dict
- | & - ^ operators and their methods
- remove raises KeyError; discard does not
- No indexing on sets
- Set holds items; dict holds key:value pairs
Practice questions
len({1, 2, 2, 3, 3, 3})?
Which creates an empty set?
Which raises KeyError for a missing item?
{1, 2, 3} & {2, 3, 4} equals
Which operator gives symmetric difference?
Which of these can be stored in a set?