map() function in Python - Time & Space Complexity
We want to understand how the time it takes to run code using the map() function changes as the input list gets bigger.
Specifically, how does the work grow when we apply a function to many items?
Analyze the time complexity of the following code snippet.
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared = list(map(square, numbers))
print(squared)
This code applies the square function to each number in the list using map() and collects the results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the
squarefunction to each item in the list. - How many times: Once for each item in the input list.
As the list gets bigger, the number of times we apply the function grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The work grows directly with the number of items; doubling the list doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items you process.
[X] Wrong: "Using map() makes the code run instantly or faster regardless of input size."
[OK] Correct: map() still applies the function to every item, so the time grows with the list size just like a loop would.
Knowing how map() scales helps you explain your code choices clearly and shows you understand how data size affects performance.
"What if the function passed to map() took longer for bigger numbers? How would that affect the time complexity?"