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.
Recipe
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:
- Building ordered collections with append/pop
- Returning fixed multi-value results from functions
- Slicing and unpacking in data processing
- Maintaining sorted sequences with
bisect
Working Example
import 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:
NamedTuplegives tuple immutability with named fieldsbisect.insortkeeps sorted order for insertionssortedreturns new list without mutating original- Tuple return packs two related lists from
partition
Deep Dive
How It Works
- Lists - Dynamic arrays; over-allocate for amortized O(1) append.
- Tuples - Fixed size at creation; smaller memory footprint than lists.
- Slicing -
start:stop:stepcreates shallow copy of sequence portion. - Sorting - Timsort; stable;
key=avoids decorating manually. - bisect - Binary search insertion point for sorted lists.
list vs tuple
| 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 |
Python Notes
# 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)Gotchas
- Shallow copy of nested list - Inner lists still shared. Fix:
copy.deepcopy. - Sorting mixed types - TypeError in Python 3. Fix: Normalize to comparable values or use
key. - bisect on unsorted list - Wrong insertion position silently. Fix: Keep invariant documented or sort first.
- += creates new tuple -
t += (1,)rebinds; does not mutate tuple (immutability). Fix: Expected - assign new tuple. - Large list as set member - Lists unhashable. Fix: Convert to tuple or use dict keyed by id.
Alternatives
| 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 |
FAQs
list or tuple for return values?
Tuple is conventional for fixed-shape returns (value, error). Use NamedTuple when fields need names.
sort vs sorted?
list.sort() mutates in place returning None. sorted(iterable) returns new list - works on any iterable.
How does negative indexing work?
-1 is last element. Slice [:-1] excludes last item.
When is bisect worth it?
Frequent inserts into a mostly sorted list where linear scan would hurt - modest sizes still fine with plain list.
Can tuples contain lists?
Yes but then tuple is unhashable. Cannot use as dict key.
What is list.extend vs +?
extend mutates in place. + creates new list - slower for large sequences.
How do I remove while iterating?
Iterate a copy or build new list - mutating during iteration skips elements.
Are list comprehensions always better?
Often for map/filter. Plain loop clearer for complex branches or side effects.
What is key= in sort?
Computes sort key once per element: sorted(users, key=lambda u: u.name.lower()).
How do I reverse in place?
items.reverse() or items[::-1] for copy.
Related
- Immutability & Hashability - hashable tuples
- Dictionaries - when lists become values
- heapq & Priority Queues - ordering by priority
- Comprehensions & Generator Expressions - building lists
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+.