Sub topic 13
Common pitfalls
This chapter assumes you know how to create sets, add and remove elements, and use the set operators. It also assumes you know that set elements must be hashable. Each pitfall below shows the mistake, what Python does, and the fix.
Writing `{}` for an empty set
Curly braces with nothing inside create an empty dictionary, not an empty set. Dictionaries claimed the {} syntax first.
empty_dict = {}
empty_set = set()
print(type(empty_dict)) # <class 'dict'>
print(type(empty_set)) # <class 'set'>
print(len(empty_set)) # 0The bug usually appears later. Code such as seen = {} followed by seen.add(x) fails with AttributeError: 'dict' object has no attribute 'add'. Always write set() for an empty set. A literal with at least one element, such as {1, 2}, is a set.
Passing a string to `set()` and `update()`
set() and update() take an iterable and add each item from it. A string is an iterable of characters, so you get characters, not the whole string.
print(sorted(set("hello"))) # ['e', 'h', 'l', 'o']
print({"hello"}) # {'hello'}
s = set()
s.update("hi")
print(sorted(s)) # ['h', 'i']
s.add("hi")
print(sorted(s)) # ['h', 'hi', 'i']To build a set holding one string, use a literal like {"hello"} or set(["hello"]). Use add for one element and update for many.
Relying on iteration order
A set has no defined order. The order you see can change between Python versions. For strings it can also change between runs, because Python randomizes string hashes at startup. A test that passes on your machine can fail on another one if it compares list(some_set) to a fixed list.
words = ["pear", "fig", "apple"]
unique = set(words)
print(sorted(unique)) # ['apple', 'fig', 'pear'] every timeUse sorted() when you need a stable order for display, tests, or output files. If you need to keep the order items first appeared in, use list(dict.fromkeys(items)). Do not use a set for that job.
Do not use pop() to get "the first" element either. It removes an arbitrary one.
Unhashable elements
Every element must be hashable. Lists, dicts, and sets are mutable and therefore unhashable. Putting one in a set raises TypeError.
try:
groups = {{1, 2}, {3}}
except TypeError as e:
print(e) # unhashable type: 'set'You have three common fixes, depending on what you hold:
| You have | Convert to | Example |
|---|---|---|
| A list of values | A tuple | `tuple([1, 2])` |
| A set of values | A `frozenset` | `frozenset({1, 2})` |
| A dict | A tuple of its items | `tuple(sorted(d.items()))` |
Remember that a tuple is hashable only if everything inside it is hashable. (1, [2]) still fails.
nested = {frozenset({1, 2}), frozenset({2, 1}), frozenset({3})}
print(len(nested)) # 2, the first two frozensets are equalYour own classes
A class that defines __eq__ without __hash__ becomes unhashable. Python sets its __hash__ to None in that case.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
try:
{Point(1, 2)}
except TypeError as e:
print(e) # unhashable type: 'Point'The simplest fix is a frozen dataclass. It generates __eq__ and a matching __hash__ from the fields.
from dataclasses import dataclass
@dataclass(frozen=True)
class FrozenPoint:
x: int
y: int
print(len({FrozenPoint(1, 2), FrozenPoint(1, 2)})) # 1Elements whose hash changes after insertion
A set stores each element in a slot chosen by its hash. If the hash changes after the element is added, the set looks in the wrong slot and can no longer find it. This happens when __hash__ depends on mutable fields.
class Box:
def __init__(self, v):
self.v = v
def __eq__(self, other):
return self.v == other.v
def __hash__(self):
return hash(self.v)
b = Box(1)
s = {b}
b.v = 2
print(b in s) # False
print(Box(1) in s) # False
print(len(s)) # 1
print(any(x is b for x in s)) # True, the object is still thereThe element is still in the set, but membership tests cannot find it. Only hash on fields that never change after the object is created. Immutable objects, such as tuples and frozen dataclasses, avoid this problem.
Values that compare equal collapse into one
A set uses equality and hash to decide whether two values are the same. In Python, 1, 1.0, and True are equal and have the same hash, so they count as one element.
mixed = {1, 1.0, True}
print(mixed) # {1}
print(len(mixed)) # 1
flags = {0, False, 0.0}
print(len(flags)) # 1Only the first value inserted is kept, so the type you get back can surprise you. If you need True and 1 to be different, store (type(x), x) pairs or keep them in separate sets.
Floats add another edge case. float("nan") is not equal to itself, so repeated NaN values can behave oddly in sets. Filter NaN out before building a set of floats.
Changing a set while looping over it
Adding or removing elements during a for loop over the same set raises RuntimeError.
nums = {1, 2, 3, 4, 5, 6}
try:
for n in nums:
if n % 2 == 0:
nums.remove(n)
except RuntimeError as e:
print(e) # Set changed size during iterationBuild a new set, or loop over a copy.
nums = {1, 2, 3, 4, 5, 6}
odds = {n for n in nums if n % 2 != 0}
print(sorted(odds)) # [1, 3, 5]
for n in list(nums): # the loop runs over a copy
if n % 2 == 0:
nums.remove(n)
print(sorted(nums)) # [1, 3, 5]The same rule applies to dictionaries. Changing the size of a container you are iterating over is almost always a bug.
Picking the wrong removal method
The three removal methods fail differently.
| Method | If the element is missing | If the set is empty |
|---|---|---|
| `remove(x)` | Raises `KeyError` | Raises `KeyError` |
| `discard(x)` | Does nothing | Does nothing |
| `pop()` | Not applicable | Raises `KeyError` |
Use remove when a missing element means your logic is wrong, and you want the error. Use discard when you only want the element gone. Guard pop() with a check such as if s: before calling it.
s = set()
if s:
s.pop()
else:
print("nothing to pop")
try:
s.pop()
except KeyError as e:
print("KeyError:", e) # KeyError: 'pop from an empty set'Using the result of an in-place method
Methods that change a set in place, such as add, update, discard, and remove, return None. Assigning their result throws your set away.
s = {1}
s = s.add(2)
print(s) # NoneCall the method on its own line: s.add(2). If you want a new set and want to keep the old one, use an operator or a method like union, which returns a new set.
Operators accept only sets, methods accept any iterable
The operators |, &, -, and ^ need sets on both sides. The named methods accept any iterable.
a = {1, 2}
print(sorted(a.union([2, 3]))) # [1, 2, 3]
try:
a | [2, 3]
except TypeError as e:
print(e) # unsupported operand type(s) for |: 'set' and 'list'This is a deliberate guard against typos. If your other operand is a list, a generator, or a dict, use the method form. The method form also avoids building a temporary set when the other operand is already an iterable.
Subset operators are not a total order
The operators <, <=, >, and >= test subset and superset relations. Two sets can be unrelated, so neither is smaller than the other.
x = {1}
y = {2}
print(x < y) # False
print(y < x) # False
print(x == y) # FalseBecause of this, sorted() on a list of sets does not give a meaningful ordering. It can return different results depending on the input order. Sort by something explicit instead, such as key=len or key=sorted.
Using a set when you need duplicates or order
A set keeps one copy of each value. If you need counts, use collections.Counter. If you need an ordered list without duplicates, use dict.fromkeys. If you need to look up elements by position, use a list. Sets also do not support indexing or slicing, so s[0] raises TypeError.
from collections import Counter
items = ["b", "a", "b", "c", "a", "b"]
print(len(set(items))) # 3, counts are lost
print(Counter(items)["b"]) # 3
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']Quick reference
Exercise
A function builds seen = {} and later calls seen.add(item). What error appears, what is the cause, and what is the fix?
Show answer
It raises AttributeError: 'dict' object has no attribute 'add'. The {} literal creates an empty dictionary, not a set. Replace it with seen = set().
Exercise
What does this code print, and why? Rewrite the loop so that it works. nums = {10, 11, 12, 13} for n in nums: if n > 11: nums.discard(n) print(sorted(nums))
Show answer
It raises RuntimeError: Set changed size during iteration before it prints anything, because the loop removes elements from the set it is iterating over. One fix is nums = {n for n in nums if n <= 11}. Another is looping over list(nums) and discarding inside the loop. Either way the result is [10, 11].
Exercise
You want a set of "groups", where each group is itself a collection of ids, and the groups [1, 2] and [2, 1] should count as the same group. What do you store in the outer set?
Show answer
Store frozenset objects, for example frozenset([1, 2]). A frozenset is hashable, so it can be an element, and two frozensets with the same members are equal regardless of order. Lists cannot be stored, and tuples would treat (1, 2) and (2, 1) as different.