Overwrite vs append behavior in Python - Performance Comparison
We want to see how the time it takes to add data changes when we either replace old data or add new data.
How does the way we add data affect how long the program runs?
Analyze the time complexity of the following code snippet.
data = []
for i in range(n):
# Overwrite behavior
data = [i]
for i in range(n):
# Append behavior
data.append(i)
This code first replaces the whole list with a new single-item list each time, then adds items one by one to the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The first loop overwrites the list each time, the second loop appends items to the list.
- How many times: Both loops run n times, but the cost inside differs.
When overwriting, each step replaces the list quickly, so time grows slowly. When appending, each step adds one item, making the list bigger and bigger.
| Input Size (n) | Approx. Operations Overwrite | Approx. Operations Append |
|---|---|---|
| 10 | 10 simple replacements | 10 appends, list grows to 10 |
| 100 | 100 simple replacements | 100 appends, list grows to 100 |
| 1000 | 1000 simple replacements | 1000 appends, list grows to 1000 |
Pattern observation: Overwrite time grows linearly but stays simple each time; append time also grows linearly but the list size grows, affecting memory.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows, whether overwriting or appending.
[X] Wrong: "Appending is always slower than overwriting because the list gets bigger."
[OK] Correct: Each append is quick and simple, so total time grows evenly. Overwriting replaces the whole list each time but still takes similar total time.
Understanding how different ways of adding data affect time helps you explain your choices clearly and shows you think about program speed in real situations.
"What if we changed the overwrite to create a new list with all previous items plus the new one each time? How would the time complexity change?"