Tutorials Python Python Lambda Functions
Ch 26 / 58
Python Intermediate 10 min read Chapter 26 of 58

Python Lambda Functions

A lambda function is a small, anonymous function defined in a single line with the lambda keyword. Unlike a regular function created with def, a lambda has no name, can have any number of parameters, but contains only a single expression (its implicit return value). Lambdas are the functional programming workhorse of Python — used with map(), filter(), sorted(), reduce(), and anywhere a short throwaway function is needed without the ceremony of a full def.

What you'll learn in this chapter
Lambda syntax with anatomy diagram
Single and multi-parameter lambdas
Lambda with map() — transform sequences
Lambda with filter() — select elements
Lambda with sorted() and reduce()
Lambda vs def — when to use each
Advertisement

Lambda Syntax & Anatomy

The lambda keyword creates an anonymous function. The syntax is compact: the keyword, then parameters (comma-separated), then a colon, then a single expression. The expression is implicitly returned — no return keyword needed or allowed.

Lambda Function — Syntax Anatomy
lambda
keyword
 
arguments
parameters (0 or more)
 
:
separator
 
expression
implicit return value
lambda x: x * 2
lambda x, y: x + y
lambda: 42
Python — lambda_syntax.py
# Traditional def function
def double(x):
    return x * 2

# Equivalent lambda function
double_lambda = lambda x: x * 2

print(double(5))         # 10
print(double_lambda(5))  # 10  — same result

# Lambda returns a function object
print(type(double_lambda))  # <class 'function'>

# Zero parameters
greet = lambda: "Hello, World!"
print(greet())              # Hello, World!

# One parameter
square = lambda x: x ** 2
print(square(7))           # 49

# Multiple parameters
add      = lambda x, y: x + y
multiply = lambda x, y, z: x * y * z
print(add(3, 4))          # 7
print(multiply(2,3,4))   # 24

# Default parameter values in lambda
power = lambda x, n=2: x ** n
print(power(3))            # 9   — default n=2
print(power(2, 10))        # 1024

# Immediately Invoked Lambda (IIFE pattern)
result = (lambda x, y: x + y)(10, 20)
print(result)               # 30
Key lambda constraints A lambda can have only a single expression — no statements, no loops, no multiple lines, no assignments. The expression's value is automatically returned. For anything more complex, use a regular def function.

Basic Lambda Examples

Lambdas support all Python expressions — arithmetic, string operations, comparisons, ternary expressions, and even calling other functions. Here are practical quick examples:

Python — lambda_basic.py
# Arithmetic
area    = lambda w, h: w * h
average = lambda *nums: sum(nums) / len(nums)
print(area(5, 3))              # 15
print(average(10,20,30))      # 20.0

# String operations
initials = lambda name: ".".join(w[0].upper() for w in name.split())
print(initials("alice smith"))  # A.S

# Ternary expression in lambda
is_even  = lambda n: n % 2 == 0
absolute = lambda x: x if x >= 0 else -x
clamp    = lambda x, lo, hi: max(lo, min(x, hi))
print(is_even(4))              # True
print(absolute(-7))            # 7
print(clamp(15, 0, 10))       # 10

# Calling built-in functions
first_char = lambda s: s[0].upper()
reverse    = lambda s: s[::-1]
print(first_char("python"))   # P
print(reverse("hello"))       # olleh

# *args and **kwargs in lambda
variadic = lambda *args: sum(args)
print(variadic(1,2,3,4))    # 10

Lambda with map()

map(function, iterable) applies a function to every element of an iterable and returns a map object (lazy iterator). Lambda is the perfect partner — you supply a one-liner transformation without defining a named function. Wrap in list() to materialise the results.

Python — lambda_map.py
# map(function, iterable) — transform every element
nums    = [1, 2, 3, 4, 5]

# Square each number
squares = list(map(lambda x: x**2, nums))
print(squares)         # [1, 4, 9, 16, 25]

# Double all values
doubled = list(map(lambda x: x * 2, nums))
print(doubled)         # [2, 4, 6, 8, 10]

# Convert strings to uppercase
fruits = ["apple", "banana", "cherry"]
upper  = list(map(lambda s: s.upper(), fruits))
print(upper)           # ['APPLE', 'BANANA', 'CHERRY']

# Convert list of strings to ints
str_nums = ["10", "20", "30"]
int_nums = list(map(int, str_nums))    # int itself is a function!
print(int_nums)        # [10, 20, 30]

# map() with multiple iterables
a = [1, 2, 3]
b = [4, 5, 6]
sums = list(map(lambda x, y: x + y, a, b))
print(sums)            # [5, 7, 9]

# map vs list comprehension (equivalent)
lc_squares  = [x**2 for x in nums]      # list comprehension
map_squares = list(map(lambda x:x**2,nums)) # map + lambda
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Lambda with filter()

filter(function, iterable) returns an iterator containing only the elements for which the function returns True. Lambda provides the predicate — a short condition — without defining a full function. Only items that pass the test are included.

Python — lambda_filter.py
# filter(function, iterable) — keep elements that pass
nums = [-4, -1, 0, 2, 5, 8, -3]

# Keep positive numbers only
positives = list(filter(lambda x: x > 0, nums))
print(positives)          # [2, 5, 8]

# Keep even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)              # [-4, 0, 2, 8]

# Filter strings by length
words      = ["Python", "is", "awesome", "and", "fun"]
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words)         # ['Python', 'awesome']

# Filter None and empty from a list
data  = ["Alice", None, "", "Bob", None, "Carol"]
valid = list(filter(lambda x: x, data))   # truthy check
print(valid)              # ['Alice', 'Bob', 'Carol']

# Filter dict list — keep high-scoring students
students = [
    {"name": "Alice", "score": 92},
    {"name": "Bob",   "score": 65},
    {"name": "Carol", "score": 87},
]
top = list(filter(lambda s: s["score"] >= 80, students))
print([s["name"] for s in top])  # ['Alice', 'Carol']

# filter vs list comprehension (equivalent)
lc_pos = [x for x in nums if x > 0]          # comprehension
ft_pos = list(filter(lambda x:x>0, nums))    # filter + lambda

Lambda with sorted() & reduce()

sorted()'s key parameter accepts any function — lambda is the most concise choice for custom sort keys. reduce() from functools repeatedly applies a two-argument function to accumulate a result.

Python — lambda_sorted_reduce.py
# ── sorted() with lambda key ─────────────────────────
words = ["banana", "apple", "cherry", "kiwi"]

# Sort by string length
print(sorted(words, key=lambda w: len(w)))
# ['kiwi', 'apple', 'banana', 'cherry']

# Sort by last character
print(sorted(words, key=lambda w: w[-1]))
# ['banana', 'apple', 'kiwi', 'cherry']

# Sort list of dicts by a field
people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob",   "age": 22},
    {"name": "Carol", "age": 27},
]
by_age = sorted(people, key=lambda p: p["age"])
print([p["name"] for p in by_age])
# ['Bob', 'Carol', 'Alice']

# Sort tuples by second element
coords = [(3,9), (1,4), (5,2)]
print(sorted(coords, key=lambda t: t[1]))
# [(5, 2), (1, 4), (3, 9)]

# Sort descending
print(sorted(words, key=lambda w: len(w), reverse=True))

# ── reduce() from functools ──────────────────────────
from functools import reduce

# Product of all numbers
nums = [1, 2, 3, 4, 5]
product = reduce(lambda acc, x: acc * x, nums)
print(product)            # 120  (1×2×3×4×5)

# Find maximum using reduce
maximum = reduce(lambda a, b: a if a > b else b, nums)
print(maximum)            # 5

# Flatten strings
words2 = ["Hello", " ", "World"]
joined = reduce(lambda a, b: a + b, words2)
print(joined)             # Hello World

Lambda in Higher-Order Functions

A higher-order function is one that takes another function as an argument or returns a function. Lambda shines here — it lets you define the function inline without naming it, keeping the code compact. This is a core pattern in functional programming.

Python — lambda_higher_order.py
# ── Functions that accept functions ──────────────────
def apply(func, value):
    return func(value)

print(apply(lambda x: x**2, 5))     # 25
print(apply(lambda x: x.upper(), "hi")) # HI

# ── Functions that RETURN lambdas ────────────────────
def multiplier(n):
    return lambda x: x * n   # returns a new function

triple = multiplier(3)
double = multiplier(2)
print(triple(7))          # 21
print(double(5))          # 10

# ── Lambda as callback / event handler ───────────────
operations = {
    "add":  lambda a, b: a + b,
    "sub":  lambda a, b: a - b,
    "mul":  lambda a, b: a * b,
    "div":  lambda a, b: a / b,
}

op = "mul"
print(operations[op](6, 7))  # 42

# ── Composing functions ───────────────────────────────
def compose(f, g):
    return lambda x: f(g(x))

add1_then_square = compose(
    lambda x: x**2,    # f — outer
    lambda x: x + 1    # g — inner
)
print(add1_then_square(4))  # (4+1)² = 25

Lambda vs def — When to Use Each

Lambda and def produce the same type of object — both are functions. The choice is stylistic and a matter of readability. The Python style guide (PEP 8) actually discourages assigning lambdas to variables — that's what def is for.

lambda
def
Anonymous — no name required
Named function with identifier
Single expression only
Multiple statements, loops, if blocks
Implicit return of the expression
Explicit return statement
No docstring support
Full docstring & type hints support
Best as throwaway function argument
Best for all reusable function definitions
Python — lambda_vs_def.py
# ✅ Good use of lambda — short, throwaway, inline
nums = [3, 1, 4, 1, 5, 9]
sorted(nums, key=lambda x: -x)  # descending sort — lambda shines here

# ❌ PEP 8 warns against assigning lambda to a variable
# Bad: f = lambda x: x**2
# Good: def f(x): return x**2

# ✅ Good use of def — complex, reusable, documented
def get_discount_price(price, discount_pct, tax_rate=0.18):
    """Calculate final price after discount and tax."""
    discounted = price * (1 - discount_pct / 100)
    final      = discounted * (1 + tax_rate)
    return round(final, 2)

# ❌ The same logic as lambda — unreadable!
# price_fn = lambda p, d, t=0.18: round(p*(1-d/100)*(1+t), 2)

# Decision guide:
# Need a function just for one argument? → lambda
# Function needs to be reused?          → def
# Function needs multiple statements?   → def
# Function needs error handling?        → def
# Sorting, map, filter one-liner?       → lambda
The PEP 8 rule on lambdas PEP 8 says: "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier." So double = lambda x: x*2 is discouraged; def double(x): return x*2 is preferred. Reserve lambda for inline, anonymous, throwaway use.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all lambda function examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every lambda example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • A lambda function is an anonymous, single-expression function created with lambda arguments: expression. The expression is implicitly returned.
  • Lambdas can have zero, one, or multiple parameters, including *args, default values and keyword arguments.
  • A lambda can contain only a single expression — no statements, loops, assignments, or multiple lines.
  • map(lambda, iterable) applies the lambda to every element and returns a lazy iterator. Wrap in list() to get a list.
  • filter(lambda, iterable) keeps only elements for which the lambda returns True.
  • sorted(iterable, key=lambda) sorts by the value returned by the lambda for each element.
  • reduce(lambda, iterable) from functools cumulatively applies the two-argument lambda to produce a single result.
  • Lambda is the standard choice for short, throwaway, inline function arguments. For anything reusable, complex, or needing documentation, use def.
  • PEP 8 discourages assigning lambdas to variables — prefer def for named functions.
⚡
Free Resource
Download our Python Lambda Functions Cheat Sheet
Lambda syntax, map, filter, sorted, reduce, higher-order functions & lambda vs def — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

A lambda function is a small, anonymous function defined with the lambda keyword in a single expression. Key differences from def:

  • Lambda has no name; def creates a named function.
  • Lambda body is a single expression; def can have multiple statements.
  • Lambda implicitly returns the expression; def needs an explicit return.
  • Both produce <class 'function'> objects and behave identically at runtime.
✓ Answer

map() returns a map object (a lazy iterator) — not a list. The map object applies the lambda to each element on demand. To get a list you must wrap it: list(map(...)).

result = map(lambda x: x**2, [1,2,3,4])
print(result)       # <map object at 0x...>
print(list(result)) # [1, 4, 9, 16]
✓ Answer

map(lambda, iterable) transforms every element — the lambda is applied to each item and the result replaces it. The output has the same number of elements as the input.

filter(lambda, iterable) selects elements — only items for which the lambda returns True are included. The output may have fewer elements than the input.

nums = [1,2,3,4,5]
print(list(map(lambda x:x*2,nums)))      # [2,4,6,8,10] — all 5
print(list(filter(lambda x:x>3,nums)))  # [4,5] — only 2
✓ Answer

Pass a lambda as the key argument to sorted(). The lambda receives each dict and returns the field value to sort by:

people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob",   "age": 22},
]
by_age = sorted(people, key=lambda p: p["age"])
# [{'name': 'Bob', 'age': 22}, {'name': 'Alice', 'age': 30}]
✓ Answer

Use lambda when:

  • The function is short, simple, and used only once (inline argument to map, filter, sorted).
  • The function is a single expression and a name would add no value.

Use def when:

  • The function is reused in multiple places.
  • The function needs more than one statement, a docstring, or type hints.
  • You are assigning the function to a variable — PEP 8 prefers def for this.
  • The function contains error handling, loops, or complex logic.
MCQ 1 of 3
What is the output of (lambda x, y: x ** y)(2, 8)?
MCQ 2 of 3
What does list(filter(lambda x: x % 2 == 0, range(6))) return?
MCQ 3 of 3
Which built-in function is used to sort a list of dicts by a field using a lambda key?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel