0
0
Pythonprogramming~5 mins

Nested lists in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested lists
O(n)
Understanding Time Complexity

When working with nested lists, it is important to understand how the time to process them grows as the lists get bigger.

We want to know how the number of steps changes when we look inside lists within lists.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

nested = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
for inner_list in nested:
    for item in inner_list:
        print(item)

This code goes through each small list inside a bigger list and prints every item.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The inner loop that visits each item in every small list.
  • How many times: Once for each item inside all the nested lists combined.
How Execution Grows With Input

As the total number of items inside all nested lists grows, the time to print them grows roughly the same way.

Input Size (total items)Approx. Operations
10About 10 prints
100About 100 prints
1000About 1000 prints

Pattern observation: The time grows directly with the total number of items inside all nested lists.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the total number of items inside the nested lists.

Common Mistake

[X] Wrong: "Because there are two loops, the time must be squared, like O(n²)."

[OK] Correct: The inner loop runs over smaller lists whose total items add up to n, so the loops together still visit each item once, not n times n.

Interview Connect

Understanding how nested lists affect time helps you explain your code clearly and shows you can think about how programs grow with data size.

Self-Check

"What if the inner lists were replaced by dictionaries? How would the time complexity change when iterating over all items?"