Python Tutorial
Python Change List Items
Lists are changeable. Assign to an index or a slice to replace items.
Change Item Value
Refer to the index number.
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)Change a Range
Change a slice. The number of items you insert can differ from the slice length.
thislist = ["apple", "banana", "cherry", "orange", "kiwi"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
thislist[1:2] = ["grape", "mango"]
print(thislist)📘 Real-World Deep Dive
Lists are mutable — in-place edits are cheap (O(1) at the end, O(n) elsewhere). Choosing the right mutation primitive saves whole-loop refactors.
Real-Life Scenario
Update a list of "scores" in place — normalise, drop the worst, and double-promote the top — without ever allocating a brand-new list.
Real-Life Example
scores: list[int] = [73, 18, 92, 41, 56, 88, 5]
# 1) normalise: subtract the min, then sort in place
lo = min(scores)
scores[:] = [s - lo for s in scores]
print("normalised :", scores)
# 2) drop the worst (currently 0 by construction)
scores.remove(0)
print("after drop :", scores)
# 3) double the top
scores.sort()
top = scores[-1]
scores[-1] = top * 2
print("after promo:", scores)
print("final :", sorted(scores, reverse=True))Expected Output
normalised : [68, 13, 87, 36, 51, 83, 0]
after drop : [68, 13, 87, 36, 51, 83]
after promo: [13, 36, 51, 68, 83, 166]
final : [166, 83, 68, 51, 36, 13]Common mistakes
- Mutating a list in a comprehension can leak; assign via
xs[:] = ...to update in place. list.sort()returnsNone— never assign its result.- Calling
pop(i)shifts all subsequent items; preferdequefor queue-heavy workloads.
🚀 Performance & Best Practices
xs[i] = vis O(1);xs.insert(i, v)is O(n).xs.append(v)is amortised O(1);xs += [v]is faster thanxs = xs + [v].- In-place edits avoid allocations — important in tight loops hitting millions of items.
🧪 Try It Yourself
- Implement
clamp(xs, lo, hi)in place. - Write
move(xs, src, dst)that moves one element to a new position without rebuilding. - Profile append-heavy workload with
listvs.collections.deque.