Lambda syntax and behavior in Python - Time & Space Complexity
We want to understand how the time it takes to run a lambda function changes as the input grows.
Specifically, how does the use of a lambda affect the speed when applied to data?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
This code uses a lambda function to square each number in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the lambda function to each item in the list.
- How many times: Once for each element in the list.
As the list gets bigger, the lambda runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lambda calls |
| 100 | 100 lambda calls |
| 1000 | 1000 lambda calls |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Lambda functions run faster because they are anonymous and short."
[OK] Correct: The speed depends on what the lambda does and how many times it runs, not just that it is a lambda.
Understanding how lambda functions behave with data helps you explain code efficiency clearly and shows you know how small functions impact performance.
"What if we replaced the map and lambda with a list comprehension? How would the time complexity change?"