Data Structures — Overview
Python ships with a rich set of data structures. Knowing which one to reach for — and why — is one of the clearest markers of Python fluency.
The landscape
Section titled “The landscape”| Structure | Ordered | Mutable | Duplicates | Import needed |
|---|---|---|---|---|
list | ✓ | ✓ | ✓ | — |
tuple | ✓ | ✗ | ✓ | — |
dict | ✓ (3.7+) | ✓ | keys: ✗ | — |
set | ✗ | ✓ | ✗ | — |
frozenset | ✗ | ✗ | ✗ | — |
deque | ✓ | ✓ | ✓ | collections |
defaultdict | ✓ | ✓ | keys: ✗ | collections |
Counter | ✓ | ✓ | keys: ✗ | collections |
namedtuple | ✓ | ✗ | ✓ | collections |
Quick mental model
Section titled “Quick mental model”Need a sequence you'll change? → listNeed a sequence that must not change? → tupleNeed named fields on a tuple? → namedtupleNeed key → value lookup? → dictNeed key → value with a safe default? → defaultdictNeed to count things? → CounterNeed fast append/pop from both ends? → dequeNeed membership tests, no duplicates? → setNeed an immutable set (e.g. dict key)? → frozensetThe rest of this chapter covers each structure in depth, with exercises after every section.