Python Data Structures

Built in data structures

  • int
  • float
  • bool
  • str
  • bytes
  • bytearray
  • complex

Main Built in collections

  • list
  • tuple
  • set
  • frozenset
  • dict

Standard Library Collections

  • deque
  • namedtuple
  • defaultdict
  • OrderedDict
  • Counter
  • ChainMap

Other Useful Built-in/stdlib Containers

  • array.array
  • memoryview
  • range

Time complexities (average / amortized unless noted)

n = number of elements, k = number of distinct keys (for maps), i = index

Sequence / list-like

Typeindex accessappendpop() endpop(i) / insert(i, x)search (x in)slicing
listO(1)amortized O(1)amortized O(1)O(n)O(n)O(k) to build slice
tupleO(1)— (immutable)O(n)O(k) to build new tuple
rangeO(1) for index & in (uses arithmetic)O(1) / O(log n) depending on value check
array.arrayO(1)amortized O(1)amortized O(1)O(n)O(n)O(k)

Mapping / associative

Typeget/set by keydeletein keyiteration order
dictaverage O(1)average O(1)O(1)insertion order (CPython 3.7+)
defaultdictsame as dictsamesamesame
mappingproxyO(1) (read-only view)O(1)same as underlying dict
ChainMaplookup O(m) worst-case (search chains)mutating affects first mapsameorder per underlying maps

Set-like

Typeaddremove (discard)membershipiteration
setaverage O(1)average O(1)average O(1)O(n)
frozensetimmutable (hashable)O(1)O(n)
Counterupdate O(k)decrement O(1)O(1) membership for keysO(k) over distinct keys

collections specialized

Typenotes
dequeappend/pop both ends O(1); random access O(n)
namedtuplelike tuple (O(1) access by index), plus named fields (attribute lookup O(1))
OrderedDictsame as dict in modern Python; historically maintained order (extra methods)
defaultdictdict + automatic default factory

Memory / views

Typenotes
memoryviewO(1) slicing/viewing, zero-copy into bytes/bytearray
bytesimmutable sequence of bytes (indexing O(1))
bytearraymutable bytes (indexing O(1))