1.2.21 · D3Introduction to Programming (Python)

Worked examples — Lists — creation, indexing, slicing, mutability

2,964 words13 min readBack to topic

The scenario matrix

Before solving anything, let us map the territory. Every list problem you will meet is one of these case classes:

# Case class What makes it tricky Covered by
A Positive index in range the baseline: offset from start Ex 1
B Negative index must convert Ex 1
C Index out of range raises IndexError (strict) Ex 1
D Slice, both ends in range length Ex 2
E Slice with step (fwd) ceiling formula Ex 2
F Slice out of range clamped, no error (forgiving) Ex 3
G Negative step / reversal walks backward Ex 4
H Empty / degenerate slice returns [], never crashes Ex 3
I Empty list [] length 0, no valid index Ex 5
J Aliasing (b = a) one list, two names Ex 6
K Copy (a[:] / .copy()) independent object Ex 6
L Mutate-in-place vs rebind append vs + Ex 7
M Word problem (real world) model data as a list Ex 8
N Exam twist (mutate in loop) the classic gotcha Ex 9

The columns "positive / negative / zero / out-of-range / limiting" from the parent all appear here. Let's clear them one by one.


Example 1 — Indexing: positive, negative, and out of range

Figure — Lists — creation, indexing, slicing, mutability

Example 2 — Slicing in range, with and without step

Figure — Lists — creation, indexing, slicing, mutability

Example 3 — Out-of-range and degenerate slices (the forgiving side)


Example 4 — Negative step and reversal

Figure — Lists — creation, indexing, slicing, mutability

Example 5 — The empty list (degenerate input)


Example 6 — Aliasing versus copying

Figure — Lists — creation, indexing, slicing, mutability

Example 7 — Mutate in place vs rebind


Example 8 — Word problem (real world)


Example 9 — Exam twist: mutating a list while looping it


Recall Self-quiz across the whole matrix

a=['p','y','t','h','o','n']; what is a[-6]? ::: 'p' (since ). Does a[5:9] on a length-3 list raise? ::: No — clamped to []; slicing is forgiving. What does a[4:1:-1] collect from [0,1,2,3,4,5]? ::: [4, 3, 2] (backward, stop 1 excluded). After b=a; b[0]=99, what is a[0]? ::: 99 — one list, two names. What is a after a = a.append(5)? ::: None — never do this. Why can mutating a list mid-loop skip elements? ::: Removal shifts items left but the pointer still advances, skipping the shifted item.


80/20 — every cell in one breath

  • Index: strict — out of range → IndexError; empty list has no legal index.
  • Slice: forgiving — clamps, returns [] for empty/degenerate spans, never crashes.
  • Negative step reverses direction; defaults flip to (last → before-first).
  • = shares one list; [:]/.copy()/list() make a real copy.
  • .append mutates + returns None; + builds a new list.
  • Never mutate a list while looping it — iterate a copy instead.

Related: Strings — indexing & slicing (same rules, immutable), Tuples (ordered but immutable), Mutability & function arguments.