Multiple parameters in Python - Time & Space Complexity
When a function takes more than one input, we want to know how its running time changes as these inputs grow.
We ask: How does the work increase when each input gets bigger?
Analyze the time complexity of the following code snippet.
def combine_lists(list1, list2):
result = []
for item1 in list1:
for item2 in list2:
result.append((item1, item2))
return result
This function pairs every item from the first list with every item from the second list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over both lists.
- How many times: Outer loop runs once per item in list1; inner loop runs once per item in list2 for each outer loop.
Each item in the first list pairs with every item in the second list, so work grows with both sizes multiplied.
| Input Size (list1, list2) | Approx. Operations |
|---|---|
| (10, 10) | 100 |
| (100, 100) | 10,000 |
| (1000, 1000) | 1,000,000 |
Pattern observation: Doubling both lists multiplies work by four; work grows fast as both inputs grow.
Time Complexity: O(n * m)
This means the time grows by multiplying the sizes of both inputs together.
[X] Wrong: "The time depends only on the bigger list size."
[OK] Correct: Because the function pairs every item from one list with every item from the other, both sizes matter equally.
Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about real problems with several factors.
"What if we changed the inner loop to only run half the size of list2? How would the time complexity change?"