Sets in Python
Store unique items with sets, remove duplicates in one step, and combine groups with union, intersection and difference.
Learning objectives
- βCreate sets and remove duplicates from a list
- βAdd and remove items with add(), update(), remove() and discard()
- βCombine sets with union, intersection, difference and symmetric difference
- βCheck subset, superset and disjoint relationships
π‘ Key points
- A set is an unordered collection of unique items: {3, 1, 2}. Duplicates are dropped automatically.
- {} creates an empty dictionary, not a set. Use set() for an empty set.
- Sets have no positions, so s[0] and slicing raise TypeError. Loop over a set or use sorted(s) for a fixed order.
- Items must be immutable (numbers, strings, tuples), but the set itself can grow and shrink.
- remove(x) raises KeyError if x is missing; discard(x) quietly does nothing.
- | union (in either), & intersection (in both), - difference (in the first only), ^ symmetric difference (in exactly one).
- x in s is fast, because sets use the same hashing idea as dictionary keys.
π» Code examples(5)
nums = {4, 2, 7, 2, 4}
print(nums)
print(len(nums))
roll_nos = [5, 3, 5, 1, 3, 5]
unique = set(roll_nos)
print(unique)
print(sorted(unique)) # a sorted list
empty = set()
print(type(empty), type({}))
{2, 4, 7}
3
{1, 3, 5}
[1, 3, 5]
<class 'set'> <class 'dict'>s = {10, 20, 30}
s.add(40)
s.add(20) # already there: no change
print(len(s))
s.discard(99) # missing: no error
s.remove(10)
# s.remove(99) # KeyError: 99
print(sorted(s))
s.update([50, 60]) # add several at once
print(sorted(s))
s.clear()
print(s)
4 [20, 30, 40] [20, 30, 40, 50, 60] set()
maths = {"Amit", "Priya", "Ravi", "Neha"}
cs = {"Priya", "Neha", "Karan"}
print(sorted(maths | cs)) # in either club
print(sorted(maths & cs)) # in both
print(sorted(maths - cs)) # maths only
print(sorted(maths ^ cs)) # in exactly one
['Amit', 'Karan', 'Neha', 'Priya', 'Ravi'] ['Neha', 'Priya'] ['Amit', 'Ravi'] ['Amit', 'Karan', 'Ravi']
a = {1, 2, 3, 4, 5}
b = {4, 5, 6}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
small = {1, 2}
print(small.issubset(a), a.issuperset(small))
print(a.isdisjoint({7, 8})) # nothing shared
{1, 2, 3, 4, 5, 6}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6}
True True
Trueword1, word2 = "school", "college"
common = set(word1) & set(word2)
print("Common letters:", sorted(common))
entries = [101, 104, 101, 107, 104, 110]
seen = set()
repeats = set()
for roll in entries:
if roll in seen:
repeats.add(roll)
seen.add(roll)
print("Entered twice:", sorted(repeats))
print("Unique entries:", len(seen))
Common letters: ['c', 'l', 'o'] Entered twice: [101, 104] Unique entries: 4
π― Practice
Q1. What is the output of print(len({1, 2, 2, 3, 3, 3}))?+
3. The set keeps only 1, 2 and 3.
Q2. How do you create an empty set?+
s = set(). Writing s = {} creates an empty dictionary.
Q3. cricket = {'Amit', 'Ravi', 'Neha'} and football = {'Ravi', 'Karan'}. Who plays cricket but not football?+
print(cricket - football) # Amit and Neha (order may vary)
Q4. Why does s[0] fail for a set?+
Sets are unordered, so their items have no positions. Loop over the set, or convert it first: sorted(s)[0].
Q5. What is the difference between remove() and discard()?+
Both delete an item. If the item is not in the set, remove() raises KeyError but discard() does nothing.
π Notes
The four collections side by side
You have now met all four built-in collections:
- list
[1, 2, 3]β ordered, changeable, duplicates allowed. Reach items by position. - tuple
(1, 2, 3)β ordered, cannot change, duplicates allowed. - dict
{"a": 1}β keyβvalue pairs, changeable, keys are unique. - set
{1, 2, 3}β unordered, changeable, every item unique.
Pick a set when you only care whether something is present, or when you need to remove duplicates or compare two groups.
Why the order looks strange
Python stores set items according to their hash value, not the order you typed them. For small whole numbers this often looks sorted, but for strings the order can change from one run of the program to the next. Never rely on the order of a set; call sorted() when you need one.
frozenset
A frozenset is a set that cannot change, just as a tuple is a list that cannot change:
vowels = frozenset("aeiou")
print("e" in vowels) # True
# vowels.add("y") # AttributeError
Because it is immutable, a frozenset can be a dictionary key or an item inside another set.
Common mistakes
- Using {} for an empty set β that is a dict.
- Putting a list inside a set:
{[1, 2]}raises TypeError: unhashable type: 'list'. Use a tuple:{(1, 2)}. - Expecting a fixed order when printing.
- Using add() with a list:
s.add([4, 5])fails. Uses.update([4, 5]).
Next: Day 15 β Modules and Packages, for reusing code that you (or Python) have already written.