Lambda vs regular functions in Python - Performance Comparison
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
lambda function in Python?Solution
Step 1: Understand lambda function definition
A lambda function is defined using thelambdakeyword and is anonymous (no name).Step 2: Compare with regular functions
Regular functions usedefand can have multiple statements, unlike lambdas which are single expressions.Final Answer:
A short, anonymous function defined with thelambdakeyword. -> Option BQuick Check:
Lambda = short anonymous function [OK]
- Thinking lambdas can have multiple statements
- Confusing lambda with regular def functions
- Believing lambdas must return None
Solution
Step 1: Recall lambda syntax
A lambda function is written aslambda parameters: expressionwithoutdeforreturn.Step 2: Check each option
lambda x: x + 5 matches the correct syntax:lambda x: x + 5. Others have syntax errors or usedef.Final Answer:
lambda x: x + 5 -> Option CQuick Check:
Lambda syntax = lambda params: expression [OK]
- Including 'def' or 'return' in lambda
- Missing colon after parameters
- Using parentheses incorrectly
add = lambda x, y: x + y
def add_func(x, y):
return x + y
print(add(3, 4))
print(add_func(3, 4))Solution
Step 1: Understand lambda and regular function behavior
Bothadd(lambda) andadd_func(regular) add two numbers and return the sum.Step 2: Evaluate the print statements
Callingadd(3, 4)andadd_func(3, 4)both return 7, so output is two lines with 7.Final Answer:
7 7 -> Option AQuick Check:
Both add functions return sum = 7 [OK]
- Thinking lambda returns string concatenation
- Confusing output with error messages
- Assuming lambda can't return values
multiply = lambda x, y:
x * y
print(multiply(2, 3))Solution
Step 1: Check lambda syntax rules
Lambda functions must have their expression on the same line as thelambdakeyword and parameters.Step 2: Analyze the code structure
The code places the expressionx * yon the next line, causing an IndentationError.Final Answer:
IndentationError because lambda body is on new line -> Option DQuick Check:
Lambda body must be on same line [OK]
- Placing lambda body on next line
- Adding colon after lambda parameters
- Thinking lambda can't take multiple arguments
Solution
Step 1: Understand sorting with key functions
Thekeyparameter expects a function that takes one argument and returns the value to sort by.Step 2: Evaluate options for correctness and efficiency
def get_second(t): return t[1] list.sort(key=get_second(t)) defines a regular function but incorrectly calls get_second(t) (causing NameError: 't' not defined). list.sort(key=lambda t: t[1]) uses a lambda inline, which is concise and common. list.sort(key=lambda t t[1]) has syntax error (missing colon). list.sort(key=get_second()) callsget_second()instead of passing the function.Step 3: Choose best practice
Using a lambda inline is best for simple, one-time use functions.Final Answer:
list.sort(key=lambda t: t[1]) -> Option AQuick Check:
Lambda inline for simple key function [OK]
- Forgetting colon in lambda
- Calling function instead of passing it
- Using multi-line def when lambda suffices
