Topic 46 of 64
List Modification
Overview
Lists are mutable — they provide methods to add, remove, and rearrange elements in place. Knowing the time complexity (O(1) vs O(n)) of each operation is critical for performance-aware coding.
Syntax
python
lst = [1, 2, 3]
# Add elements
lst.append(4) # [1, 2, 3, 4] O(1)
lst.insert(1, 10) # [1, 10, 2, 3, 4] O(n)
lst.extend([5, 6]) # adds multiple O(k)
# Remove elements
lst.pop() # removes last O(1)
lst.pop(0) # removes index 0 O(n)
lst.remove(10) # removes by value O(n)
# Other
lst.sort() # in-place sort
lst.reverse() # in-place reverse
lst.clear() # empty the listCommon Pitfalls
- list.pop(0) is O(n) because all elements shift — use collections.deque for O(1) operations on both ends.
- list.remove() removes only the FIRST occurrence — use a list comprehension to remove all occurrences.
- Interview tip: append() is O(1) amortized (list doubles capacity when full); insert(0, x) is O(n) due to shifting.
Real-World Example
Maintain a fixed-size history log using append and slicing
example
python
class HistoryLog:
def __init__(self, max_size: int = 10):
self._log: list[str] = []
self._max = max_size
def add(self, entry: str) -> None:
self._log.append(entry)
if len(self._log) > self._max:
self._log.pop(0) # remove oldest (consider collections.deque)
def get(self) -> list[str]:
return self._log.copy()