Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 15 min · revision 1

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

  1. Why it matters
  2. What Python actually copies on each operation
  3. Check your understanding
  4. Apply it
  5. Review prompt

Lessons of Arrays & Strings

  1. How a Python List Grows Concept · 20 min
  2. A Cost Table for Lists and Strings Concept · 15 min
  3. In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort Worked example · 30 min
  4. Building Strings Without Quadratic Traps Worked example · 15 min
  5. Lab: Grid Walks and Matrix Rotation Lab · 25 min
  6. 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] and len(seq): O(1) for both list and str, because length is stored in the object header and elements sit at fixed offsets.
  • Slicing seq[i:j]: O(j - i) for both list and str. Unlike NumPy arrays or memoryview over a bytearray, Python list, str and bytes slices are copies, never shared views. A parser that consumes a bytes payload four bytes at a time with data = data[4:] copies the remaining tail on every step, about n^2 / 8 bytes in total.
  • Concatenating a + b vs a.extend(b): a + b allocates a new list and copies both a (n pointers) and b (m pointers) in O(n + m). Calling a.extend(b) mutates a in place, copying only b in O(m) amortised time.
  • Inserting or deleting at index i (insert(i, x), pop(i), del a[i]): the n - i pointers after position i shift by one slot, so the cost is O(n - i): almost free near the tail, O(n) at the front (insert(0, x), pop(0)). Repeated n times at the front, that costs O(n^2).
  • Membership (x in seq) and seq.count(x): O(n) linear scan on list. On str, checking substring sub in s or s.find(sub) uses a linear-time (O(n)) search in CPython, whereas calling s.count(ch) for every character in a loop still multiplies to O(n^2).
  • String concatenation (s + t): O(len(s) + len(t)) because strings cannot mutate in place.
Text · CPython average/worst-case operation costs (n = len(seq), k = slice len)
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.
Python · comparing a + b, extend, memoryview, and insert(0) vs append+reverse
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"
)
Illustrative output (timings vary by CPU and load)
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.302ms

Look 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

Practice check · 3 questions

Choosing the cheaper operation

Evaluate list and string snippets by what gets copied.

Q1. A command-line tool runs once, checks a single user ID against `blocked` (a list of `10^6` IDs), and exits. A teammate suggests building `set(blocked)` first and then testing `user_id in` that set. Is that worth it?
Q2. A list holds `n = 1,000,000` log records in time order. A late record belongs at index `n - 5`, near the end. How does `records.insert(n - 5, rec)` compare with inserting at index `5`?
Q3. Inside a helper, you need a sorted version of the caller's 50-element list `headers` while leaving `headers` itself untouched. Which line does that?
Practice only: not graded, not saved, not evidence.

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:

  1. prepend_all(items) using out.insert(0, x) -> switch to append + reverse().
  2. flatten_all(chunks) using res = res + chunk -> switch to res.extend(chunk).
  3. strip_prefix_spaces(s) using while s and s[0] == " ": s = s[1:] -> switch to an index scan (i += 1) returning s[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:

  1. Why is s[i:j] on a str or list O(j - i) while memoryview(buf)[i:j] is O(1)?
  2. Contrast a + b and a.extend(b) for lists of lengths n and m.
  3. When is calling a + b or a[:] perfectly fine instead of a bug?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check