Change List Items
Direct Modification
Lists are mutable, meaning their elements can be changed after creation. You can modify values by assigning to an index, replacing slices, or using in-place methods like append() or extend().
Example
colors = ['red', 'green', 'blue']
# Single index assignment
colors[1] = 'yellow'
# Slice assignment (replaces part of the list)
colors[0:2] = ['black', 'white']
# Multiple indices with stride
colors[::2] = ['purple', 'orange']
print(colors) # ['purple', 'white', 'orange']
Output
['purple', 'white', 'orange']
Slice Replacement Rules
When assigning to a slice, the left side defines which elements are replaced, while the right side must be an iterable providing new values. The number of elements on each side does not have to match.
Example
numbers = [1, 2, 3, 4, 5]
# Replace 2 elements with 3 elements
numbers[1:3] = [20, 30, 40] # [1, 20, 30, 40, 4, 5]
# Replace 3 elements with 1 element
numbers[2:5] = [300] # [1, 20, 300, 5]
# Clear the list by replacing all elements
numbers[:] = []
Output
# Results shown in comments
Memory Considerations
Different list modification operations can have varying memory costs. Simple index assignment usually does not reallocate memory, while inserting or significantly extending may require moving or reallocating storage.
Operation | Memory Impact | Example |
---|---|---|
Index assignment | No reallocation | lst[0] = x |
Slice assignment | May reallocate | lst[1:3] = [...] |
Append | Occasional reallocation (overallocation strategy) | lst.append(x) |
Extend | Occasional reallocation (overallocation strategy) | lst.extend(iterable) |
Insert | Shifts elements, may reallocate | lst.insert(0, x) |