Lists & Tuples
Lists and tuples are Python's primary ordered sequences. Lists excel when you need mutability and methods like sort; tuples signal fixed records and enable hashability when contents allow.
Search across all documentation pages
Lists and tuples are Python's primary ordered sequences. Lists excel when you need mutability and methods like sort; tuples signal fixed records and enable hashability when contents allow.
nums = [3, 1, 4, 1, 5]
nums.sort()
unique_sorted = sorted(set(nums))
row = ("ada", 1842)
name, year = row
subset = nums[1:4:2]When to reach for this:
bisectimport bisect
from typing import NamedTuple
class Event(NamedTuple):
ts: float
kind: str
def top_k(items: list[int], k: int) -> list[int]:
return sorted(items, reverse=True)[:k]
def insert_timestamped(events: list[Event], ts: float, kind: str) -> None:
bisect.insort(events, Event(ts, kind))
def partition(pred, items: list[object]) -> tuple[list[object], list[object]]:
yes, no = [], []
for item in items:
(yes if pred(item) else no).append(item)
return yes, no
if __name__ == "__main__":
timeline: list[Event] = []
insert_timestamped(timeline, 1.0, "start")
insert_timestamped(timeline, 0.5, "warmup")
print(timeline)
print(top_k([4, 1, 7, 3], 2))What this demonstrates:
NamedTuple gives tuple immutability with named fieldsbisect.insort keeps sorted order for insertionssorted returns new list without mutating originalpartitionstart:stop:step creates shallow copy of sequence portion.key= avoids decorating manually.| Need | Pick |
|---|---|
| Mutate, append, sort | list |
| Dict key / set member | tuple (if hashable) |
| Function return bundle | tuple or NamedTuple |
| Homogeneous numeric buffer | array.array or numpy |
# copy vs view
a = [1, 2, 3]
b = a[:] # shallow copy
c = list(a) # same
# tuple unpacking with *
first, *middle, last = (1, 2, 3, 4)copy.deepcopy.key.t += (1,) rebinds; does not mutate tuple (immutability). Fix: Expected - assign new tuple.| Alternative | Use When | Don't Use When |
|---|---|---|
deque | Queue/stack at both ends | Need sorting/random access by index often |
array.array | Compact numeric C types | Mixed object types |
numpy.ndarray | Vectorized numerics | Small script lists |
dataclass | Mutable records with methods | Need hashable/immutable record |
Tuple is conventional for fixed-shape returns (value, error). Use NamedTuple when fields need names.
list.sort() mutates in place returning None. sorted(iterable) returns new list - works on any iterable.
-1 is last element. Slice [:-1] excludes last item.
Frequent inserts into a mostly sorted list where linear scan would hurt - modest sizes still fine with plain list.
Yes but then tuple is unhashable. Cannot use as dict key.
extend mutates in place. + creates new list - slower for large sequences.
Iterate a copy or build new list - mutating during iteration skips elements.
Often for map/filter. Plain loop clearer for complex branches or side effects.
Computes sort key once per element: sorted(users, key=lambda u: u.name.lower()).
items.reverse() or items[::-1] for copy.
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