0
0
Pythonprogramming~5 mins

map() function in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: map() function
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Applying the square function to each item in the list.
  • How many times: Once for each item in the input list.
How Execution Grows With Input

As the list gets bigger, the number of times we apply the function grows the same way.

Input Size (n)Approx. Operations
1010 function calls
100100 function calls
10001000 function calls

Pattern observation: The work grows directly with the number of items; doubling the list doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items you process.

Common Mistake

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

Interview Connect

Knowing how map() scales helps you explain your code choices clearly and shows you understand how data size affects performance.

Self-Check

"What if the function passed to map() took longer for bigger numbers? How would that affect the time complexity?"