What Is a Set?
A set is an unordered collection of unique elements. Lookups run in O(1) โ much faster than lists.
colours = {"red", "green", "blue"}
colours.add("red") # no effect, already present
print(len(colours)) # 3
Removing Duplicates From a List
nums = [1, 2, 2, 3, 3, 4] unique = list(set(nums)) # [1, 2, 3, 4]
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union {1,2,3,4,5}
print(a & b) # intersection {3}
print(a - b) # difference {1,2}
print(a ^ b) # symmetric {1,2,4,5}
Membership Testing Is Fast
big = set(range(10_000_000)) print(9_999_999 in big) # instant
When NOT to Use a Set
- Order matters โ use a list.
- You need duplicates โ use a list.
- Elements are mutable (e.g. lists) โ sets require hashable items.
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ