Lists and Mutable Sequences
A Python list is a mutable dynamic array of object references. It preserves
order, accepts mixed value types, and supports integer indexing and slicing.
names = ["Ada", "Grace", "Linus"]
first = names[0]
last = names[-1]
middle = names[1:2] # a new, shallow list
Mutation and aliasing
Assignment binds another name to the same list; it does not copy the list.
original = [[1], [2]]
alias = original
shallow = original.copy()
alias.append([3]) # changes original too
shallow[0].append(9) # nested list is still shared
Use copy.deepcopy only when recursively duplicating the complete object graph
is genuinely the intended ownership model. Clear ownership is usually easier to
reason about than defensive deep copying.
Common mutations have distinct contracts:
items.append(value) # one value at the end
items.extend(iterable) # every value from an iterable
items.insert(index, value)
last = items.pop() # remove and return
items.remove(value) # first equal value; ValueError if absent
items[1:3] = replacements # slice assignment may change length
Do not structurally mutate a list while iterating over it unless the behavior is deliberate. Iterate over a copy or build a new result instead.
Comprehensions and generators
Use a list comprehension for a readable transform or filter:
squares = [number * number for number in numbers if number >= 0]
A comprehension constructs the entire list. Use a generator expression when values can be consumed lazily:
total = sum(number * number for number in numbers)
Avoid deeply nested comprehensions; an ordinary loop communicates multi-step state changes more clearly.
Typical costs
| Operation | Typical cost |
|---|---|
| Index read/write | |
| Append or pop at end | amortized |
| Insert or delete near front/middle | |
| Membership or value search | |
| Slice of references |
Use collections.deque for frequent operations at both ends. Use a set or
dict when membership or keyed lookup dominates. A tuple expresses a fixed
sequence, but immutability of the tuple does not make referenced objects
immutable.