Predict the output
A list doubles its capacity when full, starting at 1. How many element copies happen over 16 appends?
cap, size, copies = 1, 0, 0
for _ in range(16):
if size == cap:
copies += size
cap *= 2
size += 1
print(copies)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 15
Right: copies of 1, 2, 4 and 8 elements add up to 15, fewer than the 16 appends.
Total copying stays under one copy per append, which is the amortized O(1) bound in numbers.
Why not the others?
- B 120. That is what copying on every append would cost.
- C 16. The first append fits without a copy, and the last growth happened at size 8.