1. Introduction
In Python, a lambda function is a small function that can be written in a single line without using the def keyword.
Normally, when we create a function in Python, we use the def keyword. But sometimes, we need a simple function that performs a small task. In such cases, we can use a lambda function.
A lambda function is also called an anonymous function because it does not require a function name when it is created.
Let us understand this with a simple real-life example.
Imagine you are a teacher. You want to calculate the square of a student’s marks or number. You could write a normal function, or you could use a lambda function to perform the calculation in one line.
For example:
square = lambda x: x * xprint(square(5))
Output:
25
Here, the lambda function takes the number 5, multiplies it by itself, and returns 25.
2. What Is a Lambda Function?
A lambda function is a small, anonymous function in Python that can accept any number of arguments but contains only one expression.
Let’s understand each part of this definition.
- Small function: It is generally used for simple operations.
- Anonymous function: It can be created without giving the function a name using
def. - Arguments: These are the input values passed to the function.
- One expression: The function body contains one expression whose result is returned automatically.
For example:
add = lambda a, b: a + bprint(add(10, 20))
Output:
30
In this example, the lambda function accepts two arguments, a and b. It adds them and returns the result.
Notice that we did not write return. Python automatically returns the value of the expression.
3. Syntax of a Lambda Function
The general syntax is:
lambda arguments: expression
There are three main parts.
lambda
Keyword used to create the function
arguments
Inputs accepted by the function
expression
Operation performed and value returned
Example:
multiply = lambda a, b: a * bprint(multiply(4, 5))
Output:
20
Explanation:
lambdacreates the function.a, bare the input arguments.a * bmultiplies the two arguments.multiply(4, 5)calls the function with values4and5.- The result is
20.
4. Difference Between a Normal Function and a Lambda Function
Python supports both normal functions and lambda functions. Both can perform calculations and return values, but their syntax is different.
Normal function using def
def add(a, b): return a + bprint(add(10, 20))
Output:
30
Lambda function
add = lambda a, b: a + bprint(add(10, 20))
Output:
30
Both programs produce the same output.
| Normal function | Lambda function |
|---|---|
Uses the def keyword | Uses the lambda keyword |
| Has a function name in its definition | Can be created without a named definition |
| Can contain multiple statements | Contains one expression |
Uses return to return a value explicitly | Returns the expression result automatically |
| Suitable for complex tasks | Suitable for small, simple tasks |
Important: A lambda function can be assigned to a variable, as shown above. In that case, you call it using the variable name. For reusable or complex functions, Python generally recommends using def.
5. Simple Examples of Lambda Functions
Let’s understand lambda functions with common examples.
Example 1: Addition of Two Numbers
add = lambda a, b: a + bprint(add(5, 3))
Output:
8
Explanation:
The function accepts two numbers, adds them, and returns their sum.
Example 2: Square of a Number
square = lambda x: x ** 2print(square(6))
Output:
36
Explanation:
The ** operator calculates a power. Therefore, 6 ** 2 means \(6 \times 6\), which equals 36.
Example 3: Cube of a Number
cube = lambda x: x ** 3print(cube(3))
Output:
27
Explanation:
The number 3 is multiplied by itself three times.
Example 4: Check Whether a Number Is Even
is_even = lambda x: x % 2 == 0print(is_even(8))print(is_even(7))
Output:
True
False
Explanation:
The % operator returns the remainder after division.
8 % 2equals0, so the result isTrue.7 % 2equals1, so the result isFalse.
Example 5: Find the Greater Number
maximum = lambda a, b: a if a > b else bprint(maximum(15, 25))
Output:
25
Explanation:
The conditional expression checks whether a is greater than b. If it is, it returns a; otherwise, it returns b.
Example 6: Convert Celsius to Fahrenheit
convert = lambda c: (c * 9/5) + 32print(convert(25))
Output:
77.0
This example shows how a lambda function can perform a mathematical formula.
6. How Does a Lambda Function Work?
A lambda function follows a simple process.
Step 1: Create the function
square = lambda x: x * x
Step 2: Pass an input
square(4)
Step 3: Perform the operation
4 * 4
Output: 16
The function receives the input, evaluates its expression, and returns the result.
You can also write a lambda function without assigning it to a variable:
print((lambda x: x + 10)(5))
Output:
15
Here, the lambda function is created and called immediately.
7. Lambda Functions with Multiple Arguments
A lambda function can accept more than one argument. You separate the arguments using commas.
Example: Add Three Numbers
add = lambda a, b, c: a + b + cprint(add(10, 20, 30))
Output:
60
Example: Calculate Total Price
Imagine you buy three notebooks, each costing ₹20.
total = lambda price, quantity: price * quantityprint(total(20, 3))
Output:
60
This is a practical example of how lambda functions can be used for simple calculations in billing systems.
8. Lambda Functions with if-else
Lambda functions can contain conditional expressions.
Example: Positive or Negative
check = lambda n: "Positive" if n > 0 else "Not positive"print(check(10))print(check(-5))
Output:
Positive
Not positive
The condition is evaluated when the function is called.
Example: Pass or Fail
result = lambda marks: "Pass" if marks >= 35 else "Fail"print(result(75))print(result(25))
Output:
Pass
Fail
This example can be useful for simple student-result calculations.
Remember: A lambda body can contain an expression, including a conditional expression. It cannot contain ordinary statement blocks such as if: with an indented body.
9. Lambda Function with the map() Function
The map() function applies a function to each item in an iterable, such as a list.
Lambda functions are frequently used with map() when we want to transform values.
Example: Find the Square of Every Number
numbers = [1, 2, 3, 4, 5]squares = list(map(lambda x: x ** 2, numbers))print(squares)
Output:
[1, 4, 9, 16, 25]
Explanation:
- The list contains five numbers.
lambda x: x ** 2calculates the square of each number.map()applies the lambda function to every number.list()converts the result into a list.
The output contains the square of each original number.
Example: Convert Names to Uppercase
names = ["charan", "ravi", "sai"]result = list(map(lambda name: name.upper(), names))print(result)
Output:
['CHARAN', 'RAVI', 'SAI']
The lambda function calls the upper() string method for every name.
10. Lambda Function with the filter() Function
The filter() function selects items that satisfy a condition.
A lambda function can return True or False to determine which items should be selected.
Example: Find Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]even = list(filter(lambda x: x % 2 == 0, numbers))print(even)
Output:
[2, 4, 6, 8]
Explanation:
- The lambda function checks whether each number is even.
- If the result is
True, the number is kept. - If the result is
False, the number is excluded.
Example: Filter Students Who Passed
marks = [25, 45, 80, 30, 60]passed = list(filter(lambda m: m >= 35, marks))print(passed)
Output:
[45, 80, 60]
Only marks greater than or equal to 35 are selected.
11. Lambda Function with the sorted() Function
The sorted() function arranges items in a particular order.
Its key parameter can accept a function that determines how the items should be compared. Lambda functions are useful for this purpose.
Example: Sort Numbers by Their Last Digit
numbers = [23, 11, 45, 32, 18]result = sorted(numbers, key=lambda x: x % 10)print(result)
Output:
[11, 32, 23, 45, 18]
Explanation:
The lambda function returns the last digit of each number. Python sorts the numbers according to those digits.
The last digits are 3, 1, 5, 2, 8, so the sorted order is based on 1, 2, 3, 5, 8.
Example: Sort Students by Marks
students = [ ("Ravi", 75), ("Charan", 90), ("Sai", 60)]result = sorted(students, key=lambda student: student[1])print(result)
Output:
[('Sai', 60), ('Ravi', 75), ('Charan', 90)]
Here, student[1] accesses the second item in each tuple, which represents the student’s marks.
To sort in descending order, use reverse=True:
result = sorted( students, key=lambda student: student[1], reverse=True)print(result)
Output:
[('Charan', 90), ('Ravi', 75), ('Sai', 60)]
12. Advantages of Lambda Functions
Lambda functions offer several benefits.
1. Short syntax
They allow small functions to be written in one line.
2. Useful for temporary operations
They are useful when a function is needed for a short operation and does not require a separate def definition.
3. Work well with built-in functions
They are often used with map(), filter(), and sorted().
4. Easy for simple calculations
Operations such as addition, multiplication, and simple condition checks can be expressed concisely.
5. Can accept multiple arguments
A lambda function can accept zero or more arguments, subject to normal Python argument rules, while its body remains a single expression.
13. Disadvantages of Lambda Functions
Lambda functions also have some limitations.
1. Only one expression
They cannot contain multiple ordinary statements in the function body.
2. Difficult to read when complex
A long or complicated lambda expression can be harder to understand than a normal function.
3. Not ideal for large programs
If an operation requires several steps, validation, loops, or detailed error handling, a normal function is usually more suitable.
4. Limited documentation
A lambda function cannot have a regular function body with a docstring in the same way a def function can.
5. Debugging can be less convenient
Lambda functions commonly have the name lambda in their function metadata, which can make tracebacks less informative than those from well-named functions.
14. Real-Life Applications of Lambda Functions
Lambda functions are useful in several programming situations.
| Application | Example |
|---|---|
| Student results | Check pass or fail |
| Billing systems | Calculate price × quantity |
| Data processing | Convert values in a list |
| Data analysis | Filter rows or values |
| Sorting | Sort students by marks |
| Machine learning | Supply simple transformation functions |
| Web development | Perform small data transformations |
For example, a shop billing system can calculate the total price of a product using a lambda function:
calculate_total = lambda price, quantity: price * quantityprice = 120quantity = 3print("Total:", calculate_total(price, quantity))
Output:
Total: 360
This is a simple example. A full billing application would normally use named functions for more complex tasks such as stock updates, tax calculations, and payment validation.
15. Important Interview Questions on Lambda Functions
Q1. What is a lambda function in Python?
A lambda function is an anonymous function created using the lambda keyword. It contains a single expression and returns the expression’s value automatically.
Q2. Why is a lambda function called an anonymous function?
It is called anonymous because it can be created without a named function definition using def. It can still be assigned to a variable.
Q3. Can a lambda function have multiple arguments?
Yes. For example:
add = lambda a, b: a + b
Q4. Can a lambda function contain multiple statements?
No. A lambda function body must be a single expression. That expression may contain operations such as arithmetic, a conditional expression, or a function call.
Q5. Does a lambda function require the return keyword?
No. Python automatically returns the result of its expression.
Q6. What is the difference between map() and filter()?
map()transforms every item by applying a function.filter()selects items based on a condition.
Q7. Can lambda functions be used with sorted()?
Yes. The key parameter can use a lambda function to decide how items are sorted.
Q8. Can lambda functions be recursive?
Technically, recursion is possible when a lambda function has a reference to itself, but it is generally clearer and more maintainable to use a normal named function for recursion.
16. Practice Questions
Try answering these questions yourself before checking the solutions.
1. What is the output of ` (lambda x: x + 5)(10) `?101550Error
2. Which keyword creates a lambda function?deffunctionlambdareturn
3. What is the output of ` (lambda x: x % 2 == 0)(12) `?False12TrueError
4. Which function selects items that satisfy a condition?map()filter()print()type()
Reset practice questions
17. Conclusion
A lambda function is a simple way to create a small function in Python using the lambda keyword. It accepts arguments, performs one expression, and returns the result automatically.
The most important points to remember are:
- Syntax:
lambda arguments: expression - It can accept multiple arguments.
- It does not require an explicit
returnstatement. - It is useful with
map(),filter(), andsorted(). - It is best suited to short, simple operations.
- Use
defwhen a function needs multiple statements or more complex logic.




