Guide Python Intermediate

12.17 Common Mistakes

The most common set bugs -- writing {} and silently getting a dict instead of an empty set, putting an unhashable type like a list into a set, and assuming iteration order matches insertion order.

2 min read

Using {}

{} creates an empty dict, not an empty set — a legacy of dict literal syntax getting first claim on curly braces (see 12.2 Creating Sets). Always use set() for an empty set.

>>> empty = {}
>>> type(empty)
<class 'dict'>
>>> actual_empty_set = set()
>>> type(actual_empty_set)
<class 'set'>

Unhashable Types

Trying to put a mutable type (list, dict, another set) into a set fails, because set elements must be hashable (see 12.6 Set Indexing and Ordering) — use a tuple instead if a fixed, hashable grouping is needed.

>>> s = {[1, 2], 3}
Traceback (most recent call last):
TypeError: unhashable type: 'list'

Ordering Assumptions

Assuming list(some_set) will match the order elements were added — it won’t reliably. Sort explicitly whenever output order matters.

Quick Interview Answer

“Three mistakes account for most set bugs. First, {} — it’s a dict literal, not an empty set, purely because curly braces were claimed by dict syntax first; set() is required instead. Second, putting an unhashable value like a list or another (non-frozen) set into a set — raises TypeError: unhashable type immediately, because a set can’t compute a hash slot for something whose contents could still change. Third, and the subtlest, is assuming iteration order matches insertion order — it doesn’t, it reflects the hash table’s internal layout, and code that depends on it will eventually break in a way that’s hard to reproduce.”

Common Mistakes

  • Writing config = {} intending an empty set and later calling .add() on it, only to hit AttributeError because it’s actually a dict.
  • Putting a list of tags into a set of tags directly ({["prod", "web"]}) instead of a tuple ({("prod", "web")}) or individual hashable strings.
  • Building output that depends on set iteration order without sorting first, then debugging “inconsistent” results that were never actually guaranteed to be consistent.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form