Data Structures Basics
9 examples to get you started with Python's built-in containers - 6 basic and 3 intermediate.
Search across all documentation pages
9 examples to get you started with Python's built-in containers - 6 basic and 3 intermediate.
Append, index, and slice sequences.
items = ["a", "b", "c"]
items.append("d")
first = items[0]
middle = items[1:3]Related: Lists & Tuples - sorting and bisect
Pack related values that should not change.
point = (10, 20)
x, y = point
record = ("ada", 1842)(42,).for loops.Related: Immutability & Hashability - when tuples are dict keys
Fast lookup by hashable key.
user = {"id": 1, "name": "Ada"}
user["email"] = "ada@example.com"
for key, value in user.items():
print(key, value)Related: Dictionaries - merging and views
Membership and set algebra.
tags = {"python", "data", "python"}
tags.add("ml")
assert "data" in tags
common = {"a", "b"} & {"b", "c"} # {"b"}{} only for dicts - sets need set() or {"x"} with values.in tests - great for deduplication checks.|, &, -.Related: Sets & Frozensets - frozenset as dict key
| Operation | list | dict | set |
|---|---|---|---|
| Index i | O(1) | - | - |
| Membership | O(n) | O(1)* | O(1)* |
| Append | O(1)* | - | - |
| Insert middle | O(n) | - | - |
*Average case; worst-case hash collisions degrade dict/set.
set/dict when you need fast membership.list when order and duplicates matter with index access.Related: Choosing the Right Data Structure - decision guide
Fast append/pop from both ends.
from collections import deque
queue: deque[str] = deque()
queue.append("job-1")
queue.append("job-2")
next_job = queue.popleft()list.pop(0) is O(n); deque.popleft() is O(1).maxlen drops oldest items automatically.heapq for ordering by priority.Related: collections Module - Counter and defaultdict
Avoid manual key-exists checks when building groups.
from collections import defaultdict
by_role: defaultdict[str, list[str]] = defaultdict(list)
for name, role in [("Ada", "admin"), ("Linus", "dev"), ("Guido", "dev")]:
by_role[role].append(name)setdefault when the default is a fresh mutable.Related: collections Module - full API tour
Count hashable items in one pass.
from collections import Counter
words = ["a", "b", "a", "c", "a", "b"]
counts = Counter(words)
print(counts.most_common(2)) # [('a', 3), ('b', 2)]elements() expands counts back to repeated items.Readable field access without a full class.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(3, 4)
print(p.x, p.y)dataclass is often better when you need defaults or methods.TypedDict fits JSON-shaped dicts that stay dicts at runtime.Related: TypedDict & NamedTuple - typing records
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 16, 2026