In the previous lesson, you learned how to create reusable functions using the def keyword. While normal functions are suitable for most programming tasks, sometimes you only need a small function that performs a simple operation and is used only once.
Writing a complete function with def for such small tasks can make the code longer than necessary.
Python solves this problem by providing Lambda Functions, also known as Anonymous Functions. Lambda functions allow you to create small, one-line functions without giving them a name.
Although lambda functions are short, they are extremely useful in data analysis, data science, machine learning, sorting, filtering, and many other real-world Python applications.
After completing this lesson, you will be able to:
lambda keyword.A lambda function is a small anonymous function created using the lambda keyword.
Unlike normal functions, lambda functions do not require the def keyword or a function name.
They are generally used for simple operations that can be written in a single line.
Suppose you want a function that returns the square of a number.
Using a normal function:
def square(number):
return number * number
print(square(5))
Output
25
The same operation can be written using a lambda function.
square = lambda number: number * number
print(square(5))
Output
25
The lambda version is shorter while producing the same result.
Lambda functions are called anonymous functions because they do not have a function name created with the def keyword.
They are often assigned to variables or passed directly as arguments to other functions.
lambda arguments: expression
The syntax contains three parts:
lambda keyword.Unlike normal functions, you do not write the return keyword because lambda functions automatically return the result of the expression.
greet = lambda: "Welcome to Python"
print(greet())
Output
Welcome to Python
The lambda function returns a string without using the return statement.
A lambda function can accept one parameter.
square = lambda number: number ** 2
print(square(8))
Output
64
The argument 8 is assigned to the parameter number, and the expression returns its square.
Lambda functions can also accept multiple arguments.
addition = lambda a, b: a + b
print(addition(15, 25))
Output
40
Multiple arguments are separated by commas, just like normal functions.
average = lambda a, b, c: (a + b + c) / 3
print(average(80, 90, 100))
Output
90.0
Lambda functions are often used to return True or False.
is_even = lambda number: number % 2 == 0
print(is_even(12))
print(is_even(15))
Output
True
False
| Normal Function | Lambda Function |
|---|---|
Created using def. |
Created using lambda. |
| Can contain multiple statements. | Contains only one expression. |
Requires the return keyword to return values. |
Automatically returns the expression result. |
| Suitable for large programs. | Suitable for small operations. |
| Can have documentation and complex logic. | Best for short, simple functions. |
Consider the following program.
multiply = lambda a, b: a * b
result = multiply(6, 7)
print(result)
Execution Steps
multiply.6 and 7.a and b.a * b is evaluated.result.Output
42
Lambda functions can contain only one expression.
lambda x:
print(x)
return x
This is invalid syntax.
Do not use the return keyword inside a lambda function.
If your logic requires loops, multiple conditions, or several statements, use a normal function instead.
Use meaningful parameter names whenever possible.
Choose a normal function if it makes the code easier to understand.
In this section, you learned what Python lambda functions are and why they are useful. You explored anonymous functions, the syntax of the lambda keyword, lambda functions with one or multiple arguments, Boolean expressions, and the differences between lambda functions and normal functions. You also followed the execution flow of a lambda function and reviewed common beginner mistakes. In the next section, you will learn how to use lambda functions with map(), filter(), sorted(), reduce(), conditional expressions, and function arguments to write concise and powerful Python programs.
In the previous section, you learned how to create lambda functions using the lambda keyword. Lambda functions become even more powerful when they are combined with Python’s built-in functions such as map(), filter(), sorted(), and reduce().
These functions are widely used in Python programming, data analysis, machine learning, and automation because they allow data to be processed efficiently without writing lengthy functions.
In this section, you will learn how to use lambda functions with these built-in functions and explore several practical examples.
map()The map() function applies another function to every element of an iterable such as a list or tuple.
map(function, iterable)
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda number: number ** 2, numbers))
print(result)
Output
[1, 4, 9, 16, 25]
The lambda function is applied to each element of the list.
filter()The filter() function selects only those elements that satisfy a condition.
filter(function, iterable)
numbers = [10, 15, 20, 25, 30, 35]
even_numbers = list(filter(lambda number: number % 2 == 0, numbers))
print(even_numbers)
Output
[10, 20, 30]
The lambda function returns True only for even numbers.
sorted()The sorted() function sorts elements, and the key parameter allows a lambda function to define the sorting rule.
languages = ["Python", "C", "Java", "JavaScript"]
result = sorted(languages, key=lambda language: len(language))
print(result)
Output
['C', 'Java', 'Python', 'JavaScript']
The strings are sorted according to their length instead of alphabetical order.
reduce()The reduce() function repeatedly applies a function to combine all values into a single result.
It is available in the functools module.
from functools import reduce
numbers = [10, 20, 30, 40]
total = reduce(lambda a, b: a + b, numbers)
print(total)
Output
100
The lambda function repeatedly adds two values until only one final value remains.
Lambda functions can be returned from another function.
def multiplier(number):
return lambda value: value * number
double = multiplier(2)
print(double(10))
Output
20
The returned lambda function remembers the value of number.
A lambda function can be passed directly to another function.
def calculate(function, value):
return function(value)
result = calculate(lambda number: number ** 3, 4)
print(result)
Output
64
The lambda function is passed as an argument and executed inside the calculate() function.
Lambda functions can contain conditional expressions using Python’s conditional expression syntax.
check = lambda number: "Even" if number % 2 == 0 else "Odd"
print(check(12))
print(check(15))
Output
Even
Odd
The lambda function evaluates the condition and returns one of two values.
The map() function can process more than one iterable.
list1 = [1, 2, 3]
list2 = [10, 20, 30]
result = list(map(lambda a, b: a + b, list1, list2))
print(result)
Output
[11, 22, 33]
Each pair of values is processed together.
Lambda functions are commonly used for sorting dictionaries.
students = [
{"name": "Rahul", "marks": 85},
{"name": "Neha", "marks": 92},
{"name": "Amit", "marks": 78}
]
result = sorted(students, key=lambda student: student["marks"])
print(result)
Output
[
{'name': 'Amit', 'marks': 78},
{'name': 'Rahul', 'marks': 85},
{'name': 'Neha', 'marks': 92}
]
The records are sorted according to the value of the marks key.
Consider the following program.
numbers = [2, 4, 6]
result = list(map(lambda number: number * 10, numbers))
print(result)
Execution Steps
numbers is created.map().map() produces an iterator.list() converts the iterator into a list.Output
[20, 40, 60]
map() or filter() ResultsIn Python 3, map() and filter() return iterator objects. Convert them to a list when needed.
reduce()The reduce() function must be imported from the functools module.
If the logic becomes difficult to read, use a normal function instead.
sorted()Ensure the lambda function returns the correct sorting key.
Remember that map() and filter() do not immediately create lists.
In this section, you learned how to combine Python lambda functions with map(), filter(), sorted(), and reduce() to process data efficiently. You explored lambda functions inside other functions, passing lambda functions as arguments, conditional lambda expressions, sorting dictionaries, and processing multiple iterables. You also followed the execution flow of lambda-based operations and reviewed common beginner mistakes. In the next section, you will apply these concepts through practical examples such as square calculators, employee salary sorting, student marks analysis, shopping discount calculators, temperature conversion, and sales analysis using lambda functions.
Lambda functions are widely used in real-world Python programming because they allow developers to write short, efficient, and readable code for simple operations. They are especially useful when working with collections of data, sorting records, filtering values, and performing quick calculations.
In this section, you will build practical examples using lambda functions. These examples demonstrate how lambda expressions simplify everyday programming tasks without requiring full function definitions.
This lambda function calculates the square of a number.
square = lambda number: number ** 2
print(square(9))
Output
81
The lambda function receives one argument and automatically returns its square.
The following lambda function determines whether a number is even or odd.
check = lambda number: "Even" if number % 2 == 0 else "Odd"
print(check(14))
print(check(21))
Output
Even
Odd
This example sorts students according to their marks.
students = [
("Rahul", 82),
("Neha", 95),
("Amit", 76),
("Riya", 89)
]
result = sorted(students, key=lambda student: student[1])
print(result)
Output
[
('Amit', 76),
('Rahul', 82),
('Riya', 89),
('Neha', 95)
]
The lambda function extracts the marks (index 1) for sorting.
Lambda functions are commonly used to sort dictionaries.
employees = [
{"name": "Rahul", "salary": 45000},
{"name": "Neha", "salary": 60000},
{"name": "Amit", "salary": 38000}
]
result = sorted(employees, key=lambda employee: employee["salary"])
print(result)
Output
[
{'name': 'Amit', 'salary': 38000},
{'name': 'Rahul', 'salary': 45000},
{'name': 'Neha', 'salary': 60000}
]
This program uses filter() with a lambda function to select only even numbers.
numbers = [5, 8, 11, 14, 17, 20]
result = list(filter(lambda number: number % 2 == 0, numbers))
print(result)
Output
[8, 14, 20]
This lambda function converts Celsius to Fahrenheit.
convert = lambda celsius: (celsius * 9 / 5) + 32
print(convert(30))
Output
86.0
This example applies a 10% discount to product prices.
prices = [500, 1200, 750, 300]
discounted = list(map(lambda price: price * 0.90, prices))
print(discounted)
Output
[450.0, 1080.0, 675.0, 270.0]
The lambda function is applied to every item using map().
reduce()This example calculates total sales.
from functools import reduce
sales = [1500, 2400, 1800, 3200]
total = reduce(lambda a, b: a + b, sales)
print(total)
Output
8900
The lambda function repeatedly combines two values until only one total remains.
The following program converts every name in a list to uppercase.
names = ["rahul", "neha", "amit"]
result = list(map(lambda name: name.upper(), names))
print(result)
Output
['RAHUL', 'NEHA', 'AMIT']
This example filters expensive products.
prices = [550, 1800, 950, 2200, 750]
result = list(filter(lambda price: price > 1000, prices))
print(result)
Output
[1800, 2200]
Consider the following program.
numbers = [1, 2, 3, 4]
result = list(map(lambda number: number * 5, numbers))
print(result)
Execution Steps
numbers is created.map().map() creates an iterator.Output
[5, 10, 15, 20]
Lambda functions are ideal for short expressions that fit on one line.
If multiple statements or loops are required, use a function created with def.
Lambda functions work best with map(), filter(), sorted(), and reduce().
Avoid overly complicated lambda expressions that reduce code readability.
Parameter names such as student, employee, or price make code easier to understand.
map() and filter() into a list.reduce() from the functools module.In this section, you applied Python lambda functions to practical programming tasks such as square calculation, even-or-odd checking, sorting student marks, sorting employee salaries, filtering even numbers, temperature conversion, shopping discount calculation, total sales analysis using reduce(), converting strings to uppercase, and filtering expensive products. You also learned best practices, reviewed common beginner mistakes, and followed the execution flow of lambda-based operations. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Recursion.
In this lesson, you learned how Python Lambda Functions provide a concise way to create small anonymous functions using the lambda keyword. Unlike normal functions created with the def keyword, lambda functions consist of a single expression and automatically return the result without requiring a return statement.
You explored the syntax of lambda functions, learned how to create lambda functions with one or multiple arguments, and understood the differences between lambda functions and normal functions. You also discovered how lambda functions work seamlessly with Python’s built-in functions such as map(), filter(), sorted(), and reduce(), making them ideal for data processing and transformation tasks.
Through practical examples such as square calculators, sorting student records, filtering even numbers, shopping discount calculations, temperature conversion, and sales analysis, you learned how lambda functions simplify code while improving readability and efficiency.
Although lambda functions are powerful, they should be used only for simple expressions. For complex logic involving multiple statements, loops, or extensive conditional processing, normal functions created with the def keyword remain the better choice.
lambda keyword.map(), filter(), sorted(), and reduce().A lambda function is a small anonymous function created using the lambda keyword that contains a single expression.
They are called anonymous because they are created without using the def keyword to define a named function.
No. A lambda function can contain only one expression.
return keyword?No. The result of the expression is returned automatically.
Lambda functions are best for short, simple operations, especially when used with functions such as map(), filter(), and sorted().
Yes. Lambda functions can accept any number of arguments but contain only one expression.
A normal function uses the def keyword and can contain multiple statements, while a lambda function uses the lambda keyword and contains only one expression.
reduce() a built-in function?No. In Python 3, reduce() is available in the functools module and must be imported before use.
map() with a lambda function to calculate the cubes of numbers in a list.filter() with a lambda function to extract numbers greater than 50.sorted() and a lambda function.reduce() and a lambda function to calculate the product of numbers in a list.map() used with lambda functions?filter() used with lambda functions?reduce() imported from the functools module?Create a Python program that analyzes student marks using lambda functions.
Your program should:
sorted() and a lambda function.filter().map().reduce().Students Sorted by Marks
Amit : 72
Rahul : 84
Neha : 91
Students with Marks >= 75
Rahul : 84
Neha : 91
Marks After Grace
Amit : 77
Rahul : 89
Neha : 96
Total Marks : 247
Congratulations! You have successfully learned Python Lambda Functions. You now understand how to create anonymous functions, work with lambda expressions, and combine them with map(), filter(), sorted(), and reduce() to write concise and efficient Python programs.
In the next lesson, you will explore Python Recursion: Complete Guide for Beginners. You will learn what recursion is, how recursive functions work, the importance of the base case, recursive call flow, recursion versus loops, common mistakes, optimization techniques, and practical examples such as factorial calculation, Fibonacci series generation, and tree traversal.