10.4 Modifying Lists
Updating an element by index, growing a list with append() and extend(), inserting at a position, and replacing a whole range at once with slice assignment -- all of which mutate the list in place.
All of these mutate the list in place — the list’s identity (id()) stays the same throughout; see 10.11 Copying and Mutability.
Update
Assign directly to an index to replace that single element.
>>> l = [1, 2, 3]
>>> l[0] = 99
>>> l
[99, 2, 3]
Append
Adds one item to the end — the most common way to grow a list.
>>> l.append(4)
>>> l
[99, 2, 3, 4]
Extend
Adds each item from another iterable individually — different from append(), which would add the whole iterable as one nested element.
>>> l.extend([5, 6])
>>> l
[99, 2, 3, 4, 5, 6]
Insert
Adds an item at a specific position, shifting everything after it one slot to the right — see 10.13 Performance for why this is more expensive than append().
>>> l.insert(1, 100)
>>> l
[99, 100, 2, 3, 4, 5, 6]
Replace (Slice Assignment)
Assigning to a slice replaces a whole range of elements at once, and the replacement can even be a different length than the original range.
>>> l[1:3] = [7, 8, 9]
>>> l
[99, 7, 8, 9, 3, 4, 5, 6]
Quick Interview Answer
“Every modification method here mutates the list in place rather than returning a new one — the list’s
id()never changes.l[i] = xreplaces a single element.append(x)adds exactly one item to the end;extend(iterable)unpacks and adds each item individually — a very common point of confusion, sinceappend([1, 2])nests a whole list as one element instead of adding1and2separately.insert(i, x)shifts everything after positionito make room. Slice assignment is the most powerful of the group — it can replace, grow, or shrink a range in one statement, since the replacement doesn’t need to match the original range’s length.”
Common Mistakes
- Calling
l.append([1, 2])whenl.extend([1, 2])was intended —appendnests the whole list as a single element, producing[..., [1, 2]]instead of adding1and2individually. - Using
l.insert(0, x)repeatedly in a loop instead of building the list in order and callingappend()— eachinsert(0, ...)is O(n), turning the loop into O(n²). - Forgetting slice assignment’s replacement length doesn’t need to match the slice’s length —
l[1:3] = [7, 8, 9]replaces two elements with three, growing the list.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form