List mutability in Python - Time & Space Complexity
When we change items in a list, it's important to know how long these changes take as the list grows.
We want to understand how the time to update a list item changes when the list gets bigger.
Analyze the time complexity of the following code snippet.
my_list = [0] * n
my_list[5] = 10
This code creates a list of size n and then changes the value at index 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct access and update of a list element by index.
- How many times: Exactly once in this example.
Changing one item in a list takes the same amount of time no matter how big the list is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the list grows larger.
Time Complexity: O(1)
This means updating a list item by its position takes a constant amount of time, no matter the list size.
[X] Wrong: "Changing an item in a list takes longer if the list is bigger."
[OK] Correct: Because lists in Python allow direct access by index, the update happens immediately without checking other items.
Knowing that list updates are quick helps you explain why some operations are fast and others slower, showing you understand how data structures work.
"What if we insert an item at the start of the list? How would the time complexity change?"