0
0
Pythonprogramming~5 mins

List mutability in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: List mutability
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Changing one item in a list takes the same amount of time no matter how big the list is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same even if the list grows larger.

Final Time Complexity

Time Complexity: O(1)

This means updating a list item by its position takes a constant amount of time, no matter the list size.

Common Mistake

[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.

Interview Connect

Knowing that list updates are quick helps you explain why some operations are fast and others slower, showing you understand how data structures work.

Self-Check

"What if we insert an item at the start of the list? How would the time complexity change?"