Lambda vs regular functions in Python - Performance Comparison
We want to see if using lambda functions changes how long a program takes to run compared to regular functions.
Does the way we write a function affect how fast it works as input grows?
Analyze the time complexity of the following code snippet.
# Regular function
def square(x):
return x * x
# Lambda function
square_lambda = lambda x: x * x
# Using both in a loop
for i in range(n):
a = square(i)
b = square_lambda(i)
This code defines a regular function and a lambda function that both square a number, then uses them in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop running from 0 to n-1, calling functions each time.
- How many times: n times, once per loop iteration.
Each time n grows, the loop runs more times, doing the same simple calculation each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to each function |
| 100 | About 100 calls to each function |
| 1000 | About 1000 calls to each function |
Pattern observation: The number of operations grows directly with n, no matter if using lambda or regular function.
Time Complexity: O(n)
This means the time it takes grows in a straight line as the input size grows, whether using lambda or regular functions.
[X] Wrong: "Lambda functions are slower or faster than regular functions because they are different."
[OK] Correct: Both lambda and regular functions run the same way under the hood; the time depends on how many times they are called, not how they are written.
Understanding that function style does not change time complexity helps you focus on writing clear code and analyzing real performance factors.
"What if we replaced the loop with a recursive call that calls the function n times? How would the time complexity change?"