Python Lambda Functions
Learn how to create small anonymous functions using
Python's lambda expression and use them
with sorting, filtering, mapping, and real-world data.
What You Will Learn
By the end of this lesson, you will understand how lambda functions work and when they are useful.
- Understand anonymous functions.
- Learn the syntax of a lambda expression.
- Use one or more parameters with lambda.
-
Use lambda expressions with
sorted(). -
Use lambda with
map()andfilter(). -
Understand the relationship between
lambdaanddef. - Apply lambda functions to practical data-processing problems.
What Is a Lambda Function?
A lambda function is a small anonymous function created
using the lambda keyword.
Unlike a normal function created with
def, a lambda is generally used for a
short operation that can be expressed in a single
expression.
A lambda function is a compact function expression without a traditional function name.
lambda x: x * 2
This lambda receives x and returns
x * 2.
Why Use Lambda Functions?
Lambda functions are particularly useful when you need a small function for a short period of time.
They are commonly used with functions such as
sorted(), map(), and
filter().
def double(number):
return number * 2
print(double(5))
double = lambda number: number * 2
print(double(5))
10
Both versions perform the same basic operation.
Lambda Syntax
The general syntax is:
lambda parameters: expression
A lambda expression has three important parts:
-
The
lambdakeyword. - One or more parameters.
- An expression whose result is returned.
lambda x: x + 10
Notice that there is no return keyword.
The expression's result is returned automatically.
Basic Lambda Examples
Square a Number
square = lambda x: x ** 2
print(square(6))
36
Add 5
add_five = lambda x: x + 5
print(add_five(10))
15
Convert to Uppercase
upper = lambda text: text.upper()
print(upper("python"))
PYTHON
Lambda Parameters
A lambda function can accept parameters just like a normal function.
greet = lambda name: f"Hello, {name}!"
print(greet("Ali"))
Hello, Ali!
Multiple Lambda Parameters
Lambda expressions can accept multiple parameters.
add = lambda a, b: a + b
print(add(10, 20))
30
calculate = lambda a, b, c: a + b + c
print(calculate(10, 20, 30))
60
Lambda Functions Return Automatically
A lambda function contains an expression rather than a block of statements. The result of that expression is automatically returned.
multiply = lambda x, y: x * y
result = multiply(7, 8)
print(result)
56
You cannot write a normal
return statement inside a lambda
expression.
Storing Lambda Functions
A lambda expression can be assigned to a variable.
cube = lambda x: x ** 3
print(cube(4))
64
Although this works, for reusable functions with
meaningful names and multiple statements, a normal
def function is generally clearer.
Lambda with Conditions
Lambda expressions can use Python's conditional expression syntax.
check_number = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_number(10))
print(check_number(7))
Even Odd
This is an expression-based conditional, not a normal
multi-line if block.
Lambda with sorted()
One of the most useful applications of lambda functions is custom sorting.
names = ["Ali", "Alexander", "Sara", "Muhammad"]
result = sorted(names, key=lambda name: len(name))
print(result)
['Ali', 'Sara', 'Muhammad', 'Alexander']
The lambda tells sorted() what value should
be used for comparison.
The key Parameter
The key parameter is used by functions such
as sorted() to determine how items should
be compared.
products = [
{"name": "Laptop", "price": 120000},
{"name": "Mouse", "price": 2500},
{"name": "Keyboard", "price": 5000}
]
sorted_products = sorted(
products,
key=lambda product: product["price"]
)
for product in sorted_products:
print(product)
{'name': 'Mouse', 'price': 2500}
{'name': 'Keyboard', 'price': 5000}
{'name': 'Laptop', 'price': 120000}
Descending Order
sorted_products = sorted(
products,
key=lambda product: product["price"],
reverse=True
)
Lambda with map()
The map() function applies a function to
every item in an iterable.
numbers = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, numbers)
print(list(result))
[2, 4, 6, 8, 10]
In Python 3, map() returns an
iterator. Converting it to list()
displays all resulting values at once.
Lambda with filter()
The filter() function keeps items for
which a function returns a truthy value.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = filter(
lambda x: x % 2 == 0,
numbers
)
print(list(even_numbers))
[2, 4, 6, 8]
Filter Passing Students
marks = [45, 72, 33, 89, 61, 28]
passed = filter(
lambda mark: mark >= 40,
marks
)
print(list(passed))
[45, 72, 89, 61]
Lambda with reduce()
Python's reduce() function is available
from the functools module. It repeatedly
applies a function to combine values into one result.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(
lambda a, b: a + b,
numbers
)
print(total)
15
Conceptually, the operation works like this:
((((1 + 2) + 3) + 4) + 5)
= 15
For simple totals, Python's built-in
sum() is normally clearer than
reduce(). Learn
reduce() because it is useful for
understanding functional programming and
existing Python code.
Lambda with Lists of Dictionaries
Lambda functions become particularly useful when working with structured data.
students = [
{"name": "Ali", "marks": 78},
{"name": "Sara", "marks": 92},
{"name": "Ahmed", "marks": 65},
{"name": "Hina", "marks": 88}
]
students = sorted(
students,
key=lambda student: student["marks"],
reverse=True
)
for student in students:
print(student["name"], student["marks"])
Sara 92 Hina 88 Ali 78 Ahmed 65
Real-World Lambda Examples
Example 1 — E-Commerce Product Sorting
products = [
{"name": "Phone", "price": 85000},
{"name": "Laptop", "price": 145000},
{"name": "Tablet", "price": 55000}
]
products = sorted(
products,
key=lambda item: item["price"]
)
for item in products:
print(item["name"], item["price"])
Tablet 55000 Phone 85000 Laptop 145000
Example 2 — Discounted Prices
prices = [1000, 2500, 5000, 8000]
discounted = map(
lambda price: price * 0.90,
prices
)
print(list(discounted))
[900.0, 2250.0, 4500.0, 7200.0]
Example 3 — Filter Active Users
users = [
{"name": "Ali", "active": True},
{"name": "Sara", "active": False},
{"name": "Ahmed", "active": True},
{"name": "Hina", "active": False}
]
active_users = filter(
lambda user: user["active"],
users
)
for user in active_users:
print(user["name"])
Ali Ahmed
lambda vs def
def square(x):
return x ** 2
square = lambda x: x ** 2
Both can calculate the square of a number, but they are designed for different situations.
Use lambda when a small function is needed temporarily, especially as an argument to another function.
When to prefer def
Use def for reusable functions,
complex logic, multiple statements, meaningful
documentation, and functions that deserve a
clear name.
Common Lambda Mistakes
Mistake 1 — Writing Multiple Statements
Lambda functions are designed around a single
expression. If the logic becomes complex, use
def.
Mistake 2 — Using return
Do not try to write
lambda x: return x * 2.
Instead:
lambda x: x * 2
Mistake 3 — Overusing Lambda
Just because something can be written as a lambda does not mean it should be. Readability is more important than making code as short as possible.
Mistake 4 — Forgetting map() Returns an Iterator
If you want to display the values immediately, convert the iterator to a list when appropriate:
result = map(lambda x: x * 2, [1, 2, 3])
print(list(result))
Mistake 5 — Making Lambda Too Complicated
If a lambda requires complicated nested conditions or difficult-to-read expressions, replace it with a normal named function.
Practice Exercises
Try each exercise yourself before looking for a solution.
Exercise 1 — Square Numbers
Create a lambda function that accepts a number and returns its square.
Exercise 2 — Multiply Two Values
Create a lambda function that accepts two numbers and returns their product.
Exercise 3 — Even or Odd
Create a lambda expression that returns
"Even" or "Odd".
Exercise 4 — Double Values
Use map() and lambda to double every
number in a list.
Exercise 5 — Filter Marks
Use filter() and lambda to keep only
marks greater than or equal to 50.
Exercise 6 — Sort Names
Use sorted() and lambda to sort a list
of names according to their length.
Exercise 7 — Sort Products
Given a list of product dictionaries, sort them by price using lambda.
Challenge — Smart Product Analyzer
Build a small product analyzer using lambda functions,
sorted(), map(), and
filter().
Your Task
Start with this product data:
products = [
{"name": "Laptop", "price": 120000, "stock": 5},
{"name": "Mouse", "price": 2500, "stock": 30},
{"name": "Keyboard", "price": 5000, "stock": 12},
{"name": "Monitor", "price": 45000, "stock": 3},
{"name": "Headphones", "price": 8500, "stock": 20}
]
Your program should:
- Sort products from cheapest to most expensive.
- Find products costing more than Rs. 10,000.
- Create a list containing only product prices.
- Increase every price by 5%.
- Find products with stock below 10.
Use sorted() for sorting,
filter() for selection, and
map() for transforming values.
Use lambda expressions as the small functions
passed to them.
Quick Quiz
Which keyword is used to create a lambda function?
What is the basic lambda syntax?
Does a lambda function use an explicit
return statement?
Which function is commonly used with lambda for custom sorting?
What does map() do?
What does filter() do?
Which module provides reduce()?
When is def generally better than
lambda?
What does the key parameter in
sorted() specify?
Can a lambda function accept multiple parameters?
Lesson Summary
Lambda functions provide a concise way to create small anonymous functions in Python.
-
A lambda function is created with the
lambdakeyword. -
The basic syntax is
lambda parameters: expression. - The expression result is returned automatically.
- Lambda functions can accept multiple parameters.
-
sorted()can use lambda through itskeyparameter. -
map()can transform values using a lambda. -
filter()can select values using a lambda. -
reduce()can combine values into one result. - Lambda is best for short, simple operations.
-
Use
defwhen a function becomes complex, reusable, or deserves detailed documentation.
Lambda functions are most powerful when they are
used as small pieces of logic inside tools such
as sorted(), map(),
and filter(). Keep them simple and
prioritize readable code.
You've finished Lambda Functions!
Mark this lesson complete when you are comfortable creating lambda expressions and using them with Python's data-processing functions.