Python Lists: Slicing, Copying, and Matrix Work
Most list bugs in growing Python programs are aliasing bugs wearing a disguise. A slice looks like a window onto the original data, copy() looks like a safety net, and an index assignment looks like a cheap edit â yet each of these does something subtly different from what the syntax suggests. This lesson walks through the parts of list behaviour that only matter once a program spans several files: what slicing actually allocates, how shallow copies fail on nested data, how to read and reshape two-dimensional lists, and which everyday operations are linear when you assumed they were constant. Every rule below is paired with code that demonstrates it and a measurement that proves it.
What You'll Learn
- 1Explain exactly what a slice allocates and when a copy is shared
- 2Choose between copy, slicing, list(), and deepcopy for nested data
- 3Traverse, transpose, and flatten matrices without accidental aliasing
- 4Spot list operations that are linear and switch to the right data structure
What a slice actually allocates
Python slices are not views into the underlying array the way NumPy views are. When you write original[2:6], the interpreter clamps the bounds, walks the range, and builds a brand new list object that holds references to the same elements. The container is new; the items inside it are shared. This single fact explains most slice confusion: window is original is always false, but a mutable element seen through both lists is the same object, so mutating it through one list is visible through the other.
Slice assignment is the part people forget. Assigning a shorter sequence deletes elements, assigning a longer one inserts them, and an empty stop index at position i performs a pure insertion. Out-of-range indices in a read slice are clamped rather than raised, which makes defensive slicing safe but also hides off-by-one mistakes.
original = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
window = original[2:6]
print(window, window is original) # [2, 3, 4, 5] False
print(window is original[2:6]) # False â every slice allocates
original[2:6] = [20, 30] # replacement shrinks the list
print(original) # [0, 1, 20, 30, 4, 5, 6, 7, 8, 9]
original[1:1] = [-1, -2] # empty slice = pure insertion
print(original[:5]) # [0, -1, -2, 20, 30]
print(original[100:200]) # [] â clamped, no IndexError
print(original[::-1]) # reversed copy, original untouched
The three-part form start:stop:step follows the same clamping rules, and a negative step walks backwards from the stop bound. Note the difference between original[::-1], which builds a new list, and original.reverse(), which rewrites the list in place and returns None.
Four copy methods, one shared trap
There are four idiomatic ways to copy a list: original.copy(), original[:], list(original), and copy.deepcopy(original). The first three are shallow and behave identically â they allocate a new outer list and copy the references of the elements across. Only deepcopy walks the structure and rebuilds nested containers. The result is that a shallow copy protects you from append and pop on the original, but not from mutation of an element that both lists point at.
import copy
original = [1, 2, [3, 4]]
by_copy = original.copy()
by_slice = original[:]
by_ctor = list(original)
deep = copy.deepcopy(original)
original.append(99) # structural change
print(len(by_copy), len(deep)) # 3 4 â shallow copies missed the append
original[2][0] = 999 # nested mutation
print(by_copy) # [1, 2, [999, 4]] â shared inner list
print(by_slice) # [1, 2, [999, 4]] â shared inner list
print(deep) # [1, 2, [3, 4]] â fully independent
print(original is by_copy) # False (containers differ)
print(original[2] is by_copy[2]) # True (inner list is shared)
The practical rule is depth-sensitive: shallow copies handle changes to the top level only. Configuration objects, nested records, and any structure holding dictionaries or lists need deepcopy, and deepcopy is deliberately slow â it memoises already-visited objects so cycles terminate, but the traversal cost is real. If you control the schema, copying only the mutable leaves is usually faster than a blanket deep copy.
Reading matrices stored as nested lists
A matrix in pure Python is a list of row lists, and each row is a separate object. That means len(matrix) gives the row count, len(matrix[0]) gives the column count, and ragged rows â where different rows have different lengths â are legal, which quietly breaks column-wise algorithms. Always validate rectangularity before doing arithmetic.
Transposition is the one-liner everyone should know: zip(*matrix) unpacks the rows as positional arguments and zips them back column-first. The result is tuples, so a list comprehension is needed if you require mutable rows. Building a matrix with a comprehension of comprehensions creates independent inner lists; the classic [[0] * n] * n shortcut creates n references to one row, so writing to one row changes them all.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(matrix[1][2]) # 6
print([row[0] for row in matrix]) # [1, 4, 7] â column walk
transposed = [list(col) for col in zip(*matrix)]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
bad = [[0] * 3] * 3
bad[0][1] = 7
print(bad) # [[0, 7, 0], [0, 7, 0], [0, 7, 0]]
good = [[0] * 3 for _ in range(3)]
good[0][1] = 7
print(good) # [[0, 7, 0], [0, 0, 0], [0, 0, 0]]
For multiplication, the triple loop is fine at teaching size but quadratic in the inner dimension: the cost of multiplying an r à c matrix by a c às matrix is r à c às multiply-adds. Once that number passes a few million, hand-written Python loops are the wrong tool and NumPy's vectorised multiply is the right one.
Where list time actually goes
Lists are dynamic arrays, so indexing is constant time and appends are amortised constant time, but anything that shifts elements is linear. The table below is the version worth memorising, because it decides whether a piece of code is fine at a thousand items and fatal at a million.
| Operation | Cost | What it really does | Faster alternative |
|---|---|---|---|
lst[i], lst[i] = v | O(1) | Direct slot access | â |
lst.append(v) | O(1) amortised | Grows the backing array occasionally | Pre-size with [None] * n when the length is known |
lst.insert(0, v) | O(n) | Shifts every element right | collections.deque.appendleft |
del lst[0] | O(n) | Shifts every element left | deque.popleft() |
v in lst | O(n) | Linear scan | set membership, O(1) |
lst[a:b] | O(b â a) | Allocates a new list | itertools.islice for iterators |
lst1 + lst2 | O(n + m) | Copies both into a new list | extend when you can mutate |
lst.sort(), sorted() | O(n log n) | Timsort on keys | Sort once, keep the result |
Two entries in that table cause most production surprises. v in lst inside a loop over n items turns a task that should be linear into a quadratic one, and repeated lst.insert(0, v) while reading a file makes a job scale with the square of the file size. Both have a one-line structural fix.
import time
from collections import deque
values = list(range(400_000))
start = time.perf_counter()
for _ in range(200):
399_999 in values
print("list scan ", round(time.perf_counter() - start, 4), "s")
pool = set(values)
start = time.perf_counter()
for _ in range(200):
399_999 in pool
print("set lookup", round(time.perf_counter() - start, 6), "s")
head = deque()
start = time.perf_counter()
for v in values:
head.appendleft(v)
print("deque left", round(time.perf_counter() - start, 4), "s")
On a typical machine the set lookup finishes orders of magnitude faster than the repeated list scan, even though both loops do the same logical thing. The crossover point where building a set pays for itself is often around a few hundred elements, which is well below the size where people start worrying about it.
Sorting and comparing without side effects
Two related choices separate clean list code from code that surprises its caller. The first is in-place versus functional sorting: lst.sort() rewrites the list and returns None, while sorted(lst) returns a new list and leaves the input untouched. A function that sorts its argument with lst.sort() has mutated the caller's data, which is invisible in the signature and only shows up later as an ordering that nobody asked for. Return sorted(...) from helpers unless mutation is the documented contract.
The second choice is the sort key. key= computes one decorated value per element and sorts by it, which is faster than cmp_to_key and handles strings, dates, and nested fields uniformly. Python's sort is stable, so equal keys keep their original relative order â which means sorting by two criteria is simply two passes: sort by the secondary criterion first, then by the primary one. There is no need for a compound tuple key unless you want a single pass for readability.
rows = [
{"team": "red", "score": 12},
{"team": "blue", "score": 12},
{"team": "red", "score": 7},
]
by_score = sorted(rows, key=lambda r: r["score"])
print([r["score"] for r in by_score]) # [7, 12, 12]
stable = sorted(by_score, key=lambda r: r["team"])
print([(r["team"], r["score"]) for r in stable])
# [('red', 7), ('blue', 12), ('red', 12)] â equal scores keep their order
original = [3, 1, 2]
print(sorted(original), original) # [1, 2, 3] [3, 1, 2]
Comparisons between lists work element by element and stop at the first difference, so comparing two long lists that differ only at the end is expensive. If you do that often, reduce each list to a cheap fingerprint â a length, a hash, or a sample â before comparing the whole thing.
Patterns worth keeping in the toolbox
Three small recipes cover a surprising share of day-to-day list work: chunking a long sequence into fixed-size batches, flattening one level of nesting, and rotating elements without mutating shared state. Each is clearer expressed as a short function than as a chain of index arithmetic, and each avoids the copy-and-shift costs that inline index juggling tends to hide.
from itertools import islice
def chunked(items, size):
it = iter(items)
while True:
batch = list(islice(it, size))
if not batch:
return
yield batch
def flatten(rows):
return [item for row in rows for item in row]
def rotated(items, offset):
offset %= len(items)
return items[offset:] + items[:offset]
print(list(chunked(range(10), 3))) # [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
print(flatten([[1, 2], [3], []])) # [1, 2, 3]
print(rotated([1, 2, 3, 4, 5], 2)) # [3, 4, 5, 1, 2]
chunked uses islice on a shared iterator, so it streams instead of materialising the whole input â which matters when the source is a file handle rather than a list. rotated returns a new list rather than mutating in place, keeping the caller's data intact; if you need an in-place rotation for a hot loop, rotate the slice in three reversals and the cost stays linear with no extra allocation.
Common Mistakes
Assuming a slice is a live view of the original list
Fix: Slices always build a new container; treat element objects as shared and copy them explicitly if they are mutable
Using copy() or [:] on a list that contains lists or dicts and expecting independence
Fix: Reach for copy.deepcopy, or copy only the nested objects you know will change
Building a matrix with [[0] * n] * m and then editing a row
Fix: Use a comprehension of comprehensions so every row is a distinct list object
Checking membership with in against a list inside a loop
Fix: Convert to a set once before the loop and keep the lookup constant time
Prepending with insert(0, value) while reading a large file
Fix: Append to a deque or collect forwards and reverse once at the end
Best Practices
- Pre-size a list with [None] * n only when the final length is known before the loop
- Prefer extend or unpacking over + when you can mutate the destination
- Validate that nested rows are rectangular before doing column-wise matrix work
- Sort once and reuse the sorted result instead of sorting inside a nested loop
- Document copy depth at the boundary where a list leaves a function
Interview Questions
Q1: Is lst[1:3] a view or a copy, and what are the consequences?
It is a copy: a new list object holding references to the same elements. Structural changes to the original never reach the slice, but mutating a shared element is visible through both because the element itself is shared.
Q2: Why does list multiplication on nested rows go wrong?
With [[0] * n] * m, every row is the same list object repeated m times, so writing to one row writes to all. A comprehension such as [[0] * n for _ in range(m)] builds m independent rows.
Q3: When would you replace a list with a deque?
When the workload pushes or pops from the front. list.insert(0, v) and del lst[0] shift every element, while deque.appendleft and popleft are constant time because the deque is a doubly linked block structure.
Key Takeaways
- A slice allocates a new list of shared references â the container is new, the elements are not
- copy, [:], and list() are all shallow; only deepcopy rebuilds nested containers
- Indexing and append are cheap, while insert, delete from the front, and in are linear
- Matrices need independent rows and rectangular validation before any column work
- Replace list scans with sets and front-insertions with deque as soon as the data grows