Home Course Roadmap
Home Functions Lesson 33
Lesson 33 · Functions 40–50 minutes Beginner

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.

Functions Lambda Data Processing
0%
01

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() and filter().
  • Understand the relationship between lambda and def.
  • Apply lambda functions to practical data-processing problems.
01

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.

Simple definition

A lambda function is a compact function expression without a traditional function name.

Example
lambda x: x * 2

This lambda receives x and returns x * 2.

02

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().

Normal Function
def double(number):
    return number * 2

print(double(5))
Lambda Version
double = lambda number: number * 2

print(double(5))
Output
10

Both versions perform the same basic operation.

03

Lambda Syntax

The general syntax is:

Syntax
lambda parameters: expression

A lambda expression has three important parts:

  1. The lambda keyword.
  2. One or more parameters.
  3. An expression whose result is returned.
Example
lambda x: x + 10

Notice that there is no return keyword. The expression's result is returned automatically.

04

Basic Lambda Examples

Square a Number

Example 1
square = lambda x: x ** 2

print(square(6))
Output
36

Add 5

Example 2
add_five = lambda x: x + 5

print(add_five(10))
Output
15

Convert to Uppercase

Example 3
upper = lambda text: text.upper()

print(upper("python"))
Output
PYTHON
05

Lambda Parameters

A lambda function can accept parameters just like a normal function.

One Parameter
greet = lambda name: f"Hello, {name}!"

print(greet("Ali"))
Output
Hello, Ali!
06

Multiple Lambda Parameters

Lambda expressions can accept multiple parameters.

Add Two Numbers
add = lambda a, b: a + b

print(add(10, 20))
Output
30
Three Parameters
calculate = lambda a, b, c: a + b + c

print(calculate(10, 20, 30))
Output
60
07

Lambda Functions Return Automatically

A lambda function contains an expression rather than a block of statements. The result of that expression is automatically returned.

Automatic Return
multiply = lambda x, y: x * y

result = multiply(7, 8)

print(result)
Output
56
Do not write return

You cannot write a normal return statement inside a lambda expression.

08

Storing Lambda Functions

A lambda expression can be assigned to a variable.

Stored Lambda
cube = lambda x: x ** 3

print(cube(4))
Output
64

Although this works, for reusable functions with meaningful names and multiple statements, a normal def function is generally clearer.

09

Lambda with Conditions

Lambda expressions can use Python's conditional expression syntax.

Even or Odd
check_number = lambda x: "Even" if x % 2 == 0 else "Odd"

print(check_number(10))
print(check_number(7))
Output
Even
Odd

This is an expression-based conditional, not a normal multi-line if block.

10

Lambda with sorted()

One of the most useful applications of lambda functions is custom sorting.

Sort by Length
names = ["Ali", "Alexander", "Sara", "Muhammad"]

result = sorted(names, key=lambda name: len(name))

print(result)
Output
['Ali', 'Sara', 'Muhammad', 'Alexander']

The lambda tells sorted() what value should be used for comparison.

11

The key Parameter

The key parameter is used by functions such as sorted() to determine how items should be compared.

Sort Dictionaries by Price
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)
Output
{'name': 'Mouse', 'price': 2500}
{'name': 'Keyboard', 'price': 5000}
{'name': 'Laptop', 'price': 120000}

Descending Order

Using reverse=True
sorted_products = sorted(
    products,
    key=lambda product: product["price"],
    reverse=True
)
12

Lambda with map()

The map() function applies a function to every item in an iterable.

Double Every Number
numbers = [1, 2, 3, 4, 5]

result = map(lambda x: x * 2, numbers)

print(list(result))
Output
[2, 4, 6, 8, 10]
Important

In Python 3, map() returns an iterator. Converting it to list() displays all resulting values at once.

13

Lambda with filter()

The filter() function keeps items for which a function returns a truthy value.

Find Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

even_numbers = filter(
    lambda x: x % 2 == 0,
    numbers
)

print(list(even_numbers))
Output
[2, 4, 6, 8]

Filter Passing Students

Student Example
marks = [45, 72, 33, 89, 61, 28]

passed = filter(
    lambda mark: mark >= 40,
    marks
)

print(list(passed))
Output
[45, 72, 89, 61]
14

Lambda with reduce()

Python's reduce() function is available from the functools module. It repeatedly applies a function to combine values into one result.

Calculate a Total
from functools import reduce

numbers = [1, 2, 3, 4, 5]

total = reduce(
    lambda a, b: a + b,
    numbers
)

print(total)
Output
15

Conceptually, the operation works like this:

Step-by-Step Idea
((((1 + 2) + 3) + 4) + 5)

= 15
Developer note

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.

15

Lambda with Lists of Dictionaries

Lambda functions become particularly useful when working with structured data.

Sort Students by Marks
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"])
Output
Sara 92
Hina 88
Ali 78
Ahmed 65
16

Real-World Lambda Examples

Example 1 — E-Commerce Product Sorting

Sort by Price
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"])
Output
Tablet 55000
Phone 85000
Laptop 145000

Example 2 — Discounted Prices

Apply 10% Discount
prices = [1000, 2500, 5000, 8000]

discounted = map(
    lambda price: price * 0.90,
    prices
)

print(list(discounted))
Output
[900.0, 2250.0, 4500.0, 7200.0]

Example 3 — Filter Active Users

User Filtering
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"])
Output
Ali
Ahmed
17

lambda vs def

Using def
def square(x):
    return x ** 2
Using lambda
square = lambda x: x ** 2

Both can calculate the square of a number, but they are designed for different situations.

When to prefer lambda

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.

18

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

Incorrect

Do not try to write lambda x: return x * 2.

Instead:

Correct
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:

Example
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.

19

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.

20

Challenge — Smart Product Analyzer

Build a small product analyzer using lambda functions, sorted(), map(), and filter().

Your Task

Start with this product data:

Starting 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.
Recommended tools

Use sorted() for sorting, filter() for selection, and map() for transforming values. Use lambda expressions as the small functions passed to them.

21

Quick Quiz

1

Which keyword is used to create a lambda function?

2

What is the basic lambda syntax?

3

Does a lambda function use an explicit return statement?

4

Which function is commonly used with lambda for custom sorting?

5

What does map() do?

6

What does filter() do?

7

Which module provides reduce()?

8

When is def generally better than lambda?

9

What does the key parameter in sorted() specify?

10

Can a lambda function accept multiple parameters?

22

Lesson Summary

Lambda functions provide a concise way to create small anonymous functions in Python.

  • A lambda function is created with the lambda keyword.
  • The basic syntax is lambda parameters: expression.
  • The expression result is returned automatically.
  • Lambda functions can accept multiple parameters.
  • sorted() can use lambda through its key parameter.
  • 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 def when a function becomes complex, reusable, or deserves detailed documentation.
Key takeaway

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.