Sub topic 13
Common pitfalls
This chapter assumes you can create sets, use add, remove and discard, and apply the set operators. It covers the mistakes intermediate learners make most often with sets, what Python does in each case, and how to fix it.
Pitfall 1: `{}` is a dict
Empty braces create an empty dictionary, not a set. Use set() for an empty set.
empty = {}
print(type(empty)) # <class 'dict'>
empty = set()
print(type(empty)) # <class 'set'>A non-empty literal such as {1, 2} is a set. Only the empty case is ambiguous.
Pitfall 2: Relying on order
A set has no index and no guaranteed order. Output can differ between runs, Python versions and machines, especially for strings. Never write code that depends on which element comes first.
tags = {"red", "green", "blue"}
print(sorted(tags)) # ['blue', 'green', 'red'], safe and predictableUse sorted() when you need stable output, for example in tests. Use dict.fromkeys(items) when you need to remove duplicates and keep first-seen order. For the same reason, pop() removes an arbitrary element, so don't use it to take "the first" item.
Pitfall 3: Unhashable elements
Set elements must be hashable. Lists, dicts and other sets are not, so they raise TypeError. Convert them to tuples or frozensets first.
rows = [[1, 2], [1, 2], [3, 4]]
unique = {tuple(r) for r in rows}
print(sorted(unique)) # [(1, 2), (3, 4)]
groups = {frozenset({1, 2}), frozenset({2, 1})}
print(len(groups)) # 1A tuple is hashable only if everything inside it is hashable. (1, [2]) still fails.
Pitfall 4: Confusing `remove` and `discard`
remove raises KeyError when the element is missing. discard does nothing. Choose remove when a missing element signals a bug, and discard when "make sure it's gone" is all you need.
Pitfall 5: Changing a set while looping over it
Adding or removing elements during iteration raises RuntimeError. Build a new set instead, or loop over a copy.
s = {1, 2, 3, 4}
try:
for x in s:
if x % 2 == 0:
s.remove(x)
except RuntimeError as e:
print(e) # Set changed size during iteration
s = {x for x in s if x % 2 != 0}
print(sorted(s)) # [1, 3]Another fix is for x in list(s):, which loops over a snapshot while you change the original.
Pitfall 6: Passing a string to `set()`
set() iterates its argument, so a string is split into characters. Put a single value in a literal or a list.
print(sorted(set("cat"))) # ['a', 'c', 't']
print(sorted({"cat"})) # ['cat']
print(sorted(set(["cat"]))) # ['cat']Pitfall 7: Operators need sets, methods accept any iterable
The operators |, &, - and ^ require both sides to be sets. The named methods accept any iterable.
a = {1, 2, 3}
try:
a | [3, 4]
except TypeError as e:
print(e) # unsupported operand type(s) for |: 'set' and 'list'
print(sorted(a.union([3, 4]))) # [1, 2, 3, 4]Pitfall 8: Values that compare equal collapse
Sets use equality and hashes, so 1, 1.0 and True count as the same element. The set keeps whichever one was inserted first.
mixed = {1, True, 1.0}
print(len(mixed)) # 1This matters when a column of flags and counts is mixed in one set.
Diagnosing set errors
Exercises
Exercise
A teammate writes seen = {} and then calls seen.add(5). What error occurs, and what is the fix?
Show answer
It raises AttributeError: 'dict' object has no attribute 'add', because {} creates a dict. Write seen = set() instead.
Exercise
You have data = [[1, 2], [2, 1], [1, 2]] and want the number of distinct groups, ignoring the order of items inside each group. Which expression gives it?
Show answer
len({frozenset(g) for g in data}) gives 1. Lists are unhashable, and frozenset makes [1, 2] and [2, 1] equal.