Introduction
Python provides Lambda Functions, also known as anonymous functions. Lambda functions allow you to create small, single-expression functions in a concise and readable way.
Lambda functions are commonly used when:
- A function is needed temporarily.
- A simple operation needs to be performed.
- Functions are passed as arguments to other functions.
- Working with functions such as map(), filter(), and sorted().
For example, instead of writing:
def square(x):
return x * x
You can write:
square = lambda x: x * x
Both perform the same task, but the lambda version is shorter.
In this tutorial, you will learn what lambda functions are, their syntax, examples, real-life applications, common mistakes, interview questions, and best practices.
What are Lambda Functions?
A lambda function is a small anonymous function defined using the lambda keyword.
- Lambda functions do not require the def keyword.
- They do not have a function name unless assigned to a variable.
- They can contain only one expression.
- The expression’s result is automatically returned.
Example:
square = lambda x: x * x
print(square(5))
Output:
In this example:
- lambda creates the function.
- x is the parameter.
- x * x is the expression.
- The result is returned automatically.
Why Use Lambda Functions?
Lambda functions provide:
- Shorter code
- Improved readability for simple operations
- Convenience when passing functions as arguments
- Better integration with functional programming tools
Without lambda:
def add(a, b):
return a + b
print(add(10, 20))
With lambda:
add = lambda a, b: a + b
print(add(10, 20))
Output:
Syntax
The basic syntax is:
lambda arguments: expression
Example:
lambda x: x * 2
The function:
- Accepts one argument.
- Multiplies it by 2.
- Returns the result automatically.
Lambda Function with One Argument
Example:
square = lambda number: number * number
print(square(6))
Output:
Lambda Function with Multiple Arguments
Lambda functions can accept multiple parameters.
Example:
add = lambda a, b: a + b
print(add(10, 20))
Output:
Lambda Function with Three Arguments
Example:
multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4))
Output:
Lambda Function Without Arguments
Although uncommon, lambda functions can be created without parameters.
Example:
message = lambda: "Welcome to Python"
print(message())
Output:
Lambda Function Returning Boolean Values
Example:
is_adult = lambda age: age >= 18
print(is_adult(20))
Output:
This is useful for validation.
Lambda Functions vs Normal Functions
Normal Function
def square(x):
return x * x
Lambda Function
square = lambda x: x * x
| Feature | Normal Function | Lambda Function |
|---|---|---|
| Keyword | def | lambda |
| Name Required | Yes | Optional |
| Multiple Statements | Yes | No |
| Single Expression | Yes | Yes |
| Readability | Better for complex logic | Better for simple logic |
Using Lambda Functions with map()
The map() function applies a function to each item in an iterable.
Example:
numbers = [1, 2, 3, 4]
result = list(
map(
lambda x: x * 2,
numbers
)
)
print(result)
Output:
Each number is multiplied by 2.
Using Lambda Functions with filter()
The filter() function selects elements based on a condition.
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(
filter(
lambda x: x % 2 == 0,
numbers
)
)
print(even_numbers)
Output:
Only even numbers are returned.
Using Lambda Functions with sorted()
Lambda functions are commonly used as sorting keys.
Example:
students = [
("John", 85),
("Emma", 92),
("David", 78)
]
sorted_students = sorted(
students,
key=lambda student: student[1]
)
print(sorted_students)
Output:
(‘David’, 78),
(‘John’, 85),
(‘Emma’, 92)
]
The list is sorted by marks.
Lambda Functions Inside Functions
Example:
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
print(double(10))
Output:
This demonstrates higher-order functions.
Real-Life Examples:
1. Student Grade Checker
grade = lambda marks: "Pass" if marks >= 40 else "Fail"
print(grade(55))
Output:
Educational systems often use similar logic.
2. E-Commerce Discount
discount_price = lambda price: price * 0.9
print(discount_price(1000))
Output:
Online stores frequently apply discounts.
3. Banking Interest Calculator
interest = lambda amount: amount * 0.05
print(interest(10000))
Output:
Banks use similar calculations.
4. Employee Salary Bonus
bonus = lambda salary: salary + 5000
print(bonus(30000))
Output:
5. User Validation
is_valid = lambda username: len(username) >= 5
print(is_valid("admin"))
Output:
Advantages of Lambda Functions
1. Concise Syntax
Less code compared to traditional functions.
2. Improved Readability for Simple Operations
Short functions become easier to write.
3. Useful with Functional Programming
Works seamlessly with map(), filter(), and reduce().
4. Temporary Functions
No need to create a full function definition.
5. Flexible and Reusable
Can be assigned to variables and passed around.
Limitations of Lambda Functions
1. Single Expression Only
Lambda functions cannot contain multiple statements.
Incorrect:
lambda x:
y = x * 2
return y
2. Less Readable for Complex Logic
Complex calculations should use normal functions.
3. No Multiple Return Statements
Only one expression is allowed.
Common Mistakes
1. Writing Multiple Statements
Incorrect:
lambda x:
print(x)
return x
Output:
Lambda functions allow only one expression.
2. Forgetting to Store the Function
Incorrect:
lambda x: x * 2
The function is created but not used.
double = lambda x: x * 2
3. Using Lambda for Complex Logic
Incorrect:
complex_function = lambda x: ...
For complex tasks, use normal functions.
4. Forgetting Parentheses When Calling
Incorrect:
square = lambda x: x * x
print(square)
Correct:
5. Confusing Lambda with Return
Incorrect:
lambda x: return x * x
Output:
Lambda automatically returns the expression result.
Correct:
lambda x: x * x
Best Practices
1. Use Lambda for Simple Operations
Good:
lambda x: x * 2
Avoid using lambda for large blocks of logic.
2. Prefer Normal Functions for Complex Tasks
If readability suffers, use def.
3. Use Meaningful Variable Names
square = lambda number: number * number
Instead of:
f = lambda x: x * x
4. Combine with map() and filter()
Lambda functions work especially well with these functions.
5. Keep Code Readable
Shorter code is not always better. Prioritize clarity.
Conclusion
Lambda functions are a powerful feature of Python that allow developers to create small, anonymous functions quickly and efficiently. They are especially useful for simple operations, functional programming tasks, sorting, filtering, and data transformation.
Python Lambda Function – Interview Questions
Q 1: What is a lambda function?
Q 2: How many expressions can a lambda have?
Q 3: Does lambda support multiple parameters?
Q 4: When are lambda functions used?
Q 5: Do lambda functions use return?
Python Lambda Function – Objective Questions (MCQs)
Q1. What is the correct syntax of a lambda function in Python?
Q2. What does the following code print?
square = lambda x: x ** 2
print(square(5))
Q3. Which of the following statements is true about lambda functions?
Q4. What is the output of the following code?
add = lambda x, y: x + y
print(add(3, 7))
Q5. Which of the following best describes lambda functions in Python?