Skip to content

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.

StructureOrderedMutableDuplicatesImport needed
list✓✓✓—
tuple✓✗✓—
dict✓ (3.7+)✓keys: ✗—
set✗✓✗—
frozenset✗✗✗—
deque✓✓✓collections
defaultdict✓✓keys: ✗collections
Counter✓✓keys: ✗collections
namedtuple✓✗✓collections
Need a sequence you'll change? → list
Need a sequence that must not change? → tuple
Need named fields on a tuple? → namedtuple
Need key → value lookup? → dict
Need key → value with a safe default? → defaultdict
Need to count things? → Counter
Need fast append/pop from both ends? → deque
Need membership tests, no duplicates? → set
Need an immutable set (e.g. dict key)? → frozenset

The rest of this chapter covers each structure in depth, with exercises after every section.