0
0
Pythonprogramming~5 mins

Lambda vs regular functions in Python - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Lambda vs regular functions
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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

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.
How Execution Grows With Input

Each time n grows, the loop runs more times, doing the same simple calculation each time.

Input Size (n)Approx. Operations
10About 10 calls to each function
100About 100 calls to each function
1000About 1000 calls to each function

Pattern observation: The number of operations grows directly with n, no matter if using lambda or regular function.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding that function style does not change time complexity helps you focus on writing clear code and analyzing real performance factors.

Self-Check

"What if we replaced the loop with a recursive call that calls the function n times? How would the time complexity change?"