Nested lists in Python - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The time grows directly with the total number of items inside all nested lists.
Time Complexity: O(n)
This means the time grows in a straight line with the total number of items inside the nested lists.
[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.
Understanding how nested lists affect time helps you explain your code clearly and shows you can think about how programs grow with data size.
"What if the inner lists were replaced by dictionaries? How would the time complexity change when iterating over all items?"