A Cost Table for Lists and Strings
Compare the real time and memory costs of list and string operations—indexing, slicing, concatenation, extend and membership—so you choose the cheaper primitive every time.
Contentsand lesson path
On this page
- Why it matters
- What Python actually copies on each operation
- Check your understanding
- Apply it
- Review prompt
Lessons of Arrays & Strings
- How a Python List Grows Concept · 20 min
- A Cost Table for Lists and Strings Concept · 15 min
- In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort Worked example · 30 min
- Building Strings Without Quadratic Traps Worked example · 15 min
- Lab: Grid Walks and Matrix Rotation Lab · 25 min
- Check: Array and String Drills Knowledge check · 8 questions
What you will learn
- State the cost of common list and string operations (index, append, insert at front, slice, concatenate, membership test) and pick the cheaper alternative.
- Build and compare strings efficiently, using join instead of repeated concatenation and character counts instead of repeated scans.
Prerequisites: Complexity Analysis
01. Why it matters
Two Python snippets can compute the exact same result in nearly identical syntax while differing by a factor of n in runtime. Writing out = [x] + out vs out.append(x) followed by out.reverse(), or checking if item in lst vs if item in item_set, looks harmless in code review—until n grows from 50 to 50,000 and a previously snappy job grinds to a halt.
In How a Python List Grows, you saw why a list stores contiguous pointers with spare capacity at the tail. Now add one rule for str: Python strings are immutable sequences of characters whose length and characters are fixed at allocation. Together, those two architectural facts explain every entry in CPython official operation-cost table—and let you spot hidden quadratic loops on sight rather than guessing from benchmarks.
02. What Python actually copies on each operation
Most surprises in Python sequence performance come from hidden copying or shifting of k or n items:
- Index read
seq[k]andlen(seq):O(1)for bothlistandstr, because length is stored in the object header and elements sit at fixed offsets. - Slicing
seq[i:j]:O(j - i)for bothlistandstr. Unlike NumPy arrays ormemoryviewover abytearray, Pythonlist,strandbytesslices are copies, never shared views. A parser that consumes abytespayload four bytes at a time withdata = data[4:]copies the remaining tail on every step, aboutn^2 / 8bytes in total. - Concatenating
a + bvsa.extend(b):a + ballocates a new list and copies botha(npointers) andb(mpointers) inO(n + m). Callinga.extend(b)mutatesain place, copying onlybinO(m)amortised time. - Inserting or deleting at index
i(insert(i, x),pop(i),del a[i]): then - ipointers after positionishift by one slot, so the cost isO(n - i): almost free near the tail,O(n)at the front (insert(0, x),pop(0)). Repeatedntimes at the front, that costsO(n^2). - Membership (
x in seq) andseq.count(x):O(n)linear scan onlist. Onstr, checking substringsub in sors.find(sub)uses a linear-time (O(n)) search in CPython, whereas callings.count(ch)for every character in a loop still multiplies toO(n^2). - String concatenation (
s + t):O(len(s) + len(t))because strings cannot mutate in place.
Operation list str Cheaper alternative
------------------------------------------------------------------------------------
seq[i], len(seq) O(1) O(1) -
seq[i:j] O(j - i) copy O(j - i) copy index or memoryview
append(x) / pop() O(1) amort / O(1) n/a (immutable) -
insert(0, x) / pop(0) O(n) n/a collections.deque
a + b vs a.extend(b) O(n+m) vs O(m)* O(n+m) extend / "".join()
x in seq O(n) O(n) substring set / dict for O(1)
* extend(b) is O(len(b)) amortized when b is sized.import timeit
a = [1, 2, 3]
b = [4, 5]
combined = a + b
print("a + b:", combined, "| original a:", a)
a.extend(b)
print("after extend:", a)
buf = bytearray(b"abcdef")
view = memoryview(buf)
sub = view[2:5]
print("memoryview slice bytes:", bytes(sub))
n = 5_000
t_ins0 = min(
timeit.repeat(
"out = []; [out.insert(0, i) for i in range(n)]",
setup=f"n = {n}",
repeat=3,
number=1,
)
)
t_app_rev = min(
timeit.repeat(
"out = []; [out.append(i) for i in range(n)]; out.reverse()",
setup=f"n = {n}",
repeat=3,
number=1,
)
)
print(
f"n={n}: insert(0)={t_ins0 * 1000:.2f}ms "
f"vs append+reverse={t_app_rev * 1000:.3f}ms"
)a + b: [1, 2, 3, 4, 5] | original a: [1, 2, 3]
after extend: [1, 2, 3, 4, 5]
memoryview slice bytes: b'cde'
n=5000: insert(0)=4.91ms vs append+reverse=0.302msLook at the timing contrast even at n = 5,000: insert(0, i) in a loop took 4.91 ms while append plus a single reverse() took 0.302 ms on our lab machine—and because insert(0) is O(n^2) while append + reverse is O(n), that gap widens rapidly at n = 50,000 (roughly 100x slower for insert(0) vs 10x for append + reverse). What if you replaced a.extend(b) with a = a + b inside a loop that merges 1,000 short lists of length 5? Each a + b copies the growing prefix a, turning an O(N) merge into O(N^2) (5 + 10 + 15 + ... + 5,000 pointer copies instead of 5,000).
Trace the same hidden copy cost on the record parser above, reading a 1,000,000-byte payload with data = data[4:]: the first slice copies 999,996 bytes into a fresh bytes object, the next 999,992, and so on, about 1.25 * 10^11 copied bytes over 250,000 records. By contrast, memoryview(buf)[2:5] over a bytearray creates a lightweight wrapper referencing the exact same byte buffer at offset 2 (O(1) time and O(1) extra space), because bytearray stores raw contiguous bytes whereas Python list holds object pointers and str uses immutable 1-, 2-, or 4-byte code-point arrays.
Notice two subtleties in CPython official complexity documentation that frequently trip up learners. First, x in lst is an O(n) linear scan over element equality, whereas forward substring search sub in s or s.find(sub) uses CPython linear-time (O(n)) two-way substring matching (while reverse search s.rfind(sub) has a worst-case bound of O(n * len(sub))). Still, searching a list of 100,000 blocked IDs inside a loop over q incoming requests costs O(n * q), which is why converting the list once to a set (O(n) build) drops every subsequent x in blocked_set check to O(1) expected time (O(n + q) total). The conversion pays off only because the set is reused: building it already scans all n items and allocates a new table, so for a single lookup a plain x in lst scan does the same O(n) work without the extra memory. Second, len(seq) is O(1) on every built-in sequence (list, tuple, str, bytes, range) because the container stores its length in its C header rather than counting elements.
Simplification boundary: our cost table assumes element equality (==) itself runs in O(1) time (true for small integers or short strings). Comparing two 10,000-character strings inside x in lst multiplies each element check by string length, and calling a.extend(gen) on a generator also pays whatever work the generator performs to yield its items.
When you should NOT avoid a + b or slices: when a and b are small and joined once (outside a loop), or when you deliberately need a fresh copy so mutating the result does not mutate the caller list a, a + b or a[:] is clear, Pythonic, and cheap (O(n) once). Avoiding slices everywhere by hand-coding index loops on 10-element config lists adds clutter without measurable gain (and remember memoryview only works on buffer-protocol byte objects like bytes and bytearray, not arbitrary list or Unicode str).
03. Check your understanding
04. Apply it
Inspect three helper functions in a scratch script and rewrite each without quadratic copying, measuring n = 10,000 with timeit before and after to verify the speedup:
prepend_all(items)usingout.insert(0, x)-> switch toappend+reverse().flatten_all(chunks)usingres = res + chunk-> switch tores.extend(chunk).strip_prefix_spaces(s)usingwhile s and s[0] == " ": s = s[1:]-> switch to an index scan (i += 1) returnings[i:]once at the end.
Verify all three pairs return identical outputs with assert across empty, single-element, and long inputs before learning four O(1)-space in-place array algorithms in In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort.
05. Review prompt
Without looking back:
- Why is
s[i:j]on astrorlistO(j - i)whilememoryview(buf)[i:j]isO(1)? - Contrast
a + banda.extend(b)for lists of lengthsnandm. - When is calling
a + bora[:]perfectly fine instead of a bug?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.