To use lambda functions in Python, write lambda, the parameters, a colon and one expression. Python returns that expression’s value automatically, so a lambda is a tiny unnamed function you can pass straight into sorted(), filter() or map():
square = lambda x: x * x
print(square(7)) # 49
print(sorted(["Ohio", "Iowa", "Texas"], key=lambda s: len(s)))
Quick setup note: my test machine had Python 3.12.5 on Windows 11, and each output block is a straight copy of what Command Prompt printed.
In this tutorial, we’ll cover the syntax, sorting keys, filter/map/reduce, if-else lambdas, closures and when you should pick def instead.
What is the syntax of a lambda function in Python?
The pattern is lambda parameters: expression, with zero or more parameters and defaults allowed. Here’s a sales-tax helper written both ways:
add_tax = lambda price, rate=0.0825: round(price * (1 + rate), 2)
def add_tax_def(price, rate=0.0825):
return round(price * (1 + rate), 2)
print(add_tax(49.99))
print(add_tax_def(49.99))
print(add_tax(49.99, rate=0.06))
print(add_tax.__name__, "vs", add_tax_def.__name__)
Output:
54.11
54.11
52.99
<lambda> vs add_tax_def

def version return the same total; the only visible difference is the function name.Every lambda is named <lambda>. If you need a name, docs or several lines, use a regular function definition with a return statement.
How do you sort a list with a lambda key in Python?
This is where I use lambdas the most. The key function picks the value to compare, so a lambda sorts dicts by any field:
orders = [
{"customer": "Megan Bowen", "total": 128.40, "date": "2026-03-14"},
{"customer": "Alex Wilber", "total": 42.75, "date": "2026-01-09"},
{"customer": "Adele Vance", "total": 310.00, "date": "2026-02-22"},
{"customer": "Lee Gu", "total": 42.75, "date": "2026-02-01"},
]
for o in sorted(orders, key=lambda o: o["total"], reverse=True):
print(f'{o["customer"]:<12} ${o["total"]:.2f}')
by_total_then_date = sorted(orders, key=lambda o: (o["total"], o["date"]))
print([o["customer"] for o in by_total_then_date])
biggest = max(orders, key=lambda o: o["total"])
print("Largest order:", biggest["customer"], f'${biggest["total"]:.2f}')
Output:
Adele Vance $310.00
Megan Bowen $128.40
Alex Wilber $42.75
Lee Gu $42.75
['Alex Wilber', 'Lee Gu', 'Megan Bowen', 'Adele Vance']
Largest order: Adele Vance $310.00

max().A tuple key sorts by the first item, then the next on ties; see sorting by the second element of a tuple. max() takes the same key, as in finding the maximum value with max().
Use lambda with filter(), map() and reduce() in Python
Each of these takes a function first. filter() keeps items where the lambda is true, map() transforms each one, and reduce() folds them into one value:
from functools import reduce
prices = [19.99, 5.49, 120.00, 64.50, 3.75]
over_20 = list(filter(lambda p: p > 20, prices))
with_tax = list(map(lambda p: round(p * 1.0825, 2), prices))
cart_total = reduce(lambda total, p: total + p, prices, 0)
print("filter:", over_20)
print("map: ", with_tax)
print(f"reduce: ${cart_total:.2f}")
print("comprehension:", [round(p * 1.0825, 2) for p in prices if p > 20])
Output:
filter: [120.0, 64.5]
map: [21.64, 5.94, 129.9, 69.82, 4.06]
reduce: $213.73
comprehension: [129.9, 69.82]

filter() keeps the prices over $20.00, map() adds tax to each one, and reduce() sums the cart.Both filter() and map() return lazy iterators, so wrap them in list(). See the map() function in Python and the reduce() function in Python.
The last line gets the same taxed prices with a Python list comprehension, often easier to read. More options are in ways to filter lists in Python.
Can a Python lambda use if-else or return another function?
Yes. You can’t put an if statement in a lambda, but you can use a if condition else b. A function can also return a lambda that remembers its arguments (a closure):
shipping = lambda total: 0.00 if total >= 50 else 5.99
print([shipping(t) for t in (19.99, 50.00, 75.25)])
def make_discount(pct):
return lambda price: round(price * (1 - pct / 100), 2)
black_friday = make_discount(25)
print(black_friday(80.00), black_friday(19.99))
fees = [lambda amt: amt * r for r in (0.01, 0.02, 0.03)]
print("late binding:", [f(100) for f in fees])
fees = [lambda amt, r=r: amt * r for r in (0.01, 0.02, 0.03)]
print("fixed: ", [f(100) for f in fees])
Output:
[5.99, 0.0, 0.0]
60.0 14.99
late binding: [3.0, 3.0, 3.0]
fixed: [1.0, 2.0, 3.0]

Watch the late binding line: loop lambdas read r when they run, so all three used 0.03. A default, r=r, freezes each value. For more, see passing a function as a parameter in Python.
What are the limitations of lambda functions in Python?
You get exactly one expression. Statements like return, assignments or loops aren’t allowed, and tracebacks show <lambda> instead of a useful name:
import traceback
try:
compile("double = lambda x: return x * 2", "demo.py", "exec")
except SyntaxError as err:
print("SyntaxError:", err.msg)
to_cents = lambda dollars: int(dollars * 100)
try:
to_cents(None)
except TypeError as err:
print("TypeError:", err)
print("Traceback names the function:", traceback.extract_tb(err.__traceback__)[-1].name)
Output:
SyntaxError: invalid syntax
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Traceback names the function: <lambda>
Lambdas also can’t carry a docstring or type hints, and PEP 8 recommends def over f = lambda .... My rule of thumb: if it fits inside the call that uses it, keep the lambda; otherwise write a function.
Using lambdas in data or GUI code? These pick up from here:
- Lambda functions on a pandas DataFrame
- Apply a function to each row in pandas
- Tkinter button command (with lambda arguments)
- Built-in functions in Python
Frequently asked questions
What is a lambda function in Python?
It’s a small anonymous function you write with the lambda keyword. It returns the value of one expression.
Can a lambda function have multiple arguments?
Yes. Separate them with commas, as in lambda a, b=2: a * b. Defaults, *args and **kwargs work too.
Can a lambda contain multiple lines or statements?
No. The body is one expression, so you’ll need def for loops, assignments or return.
Is a lambda faster than a regular function?
No. Both create the same kind of function object, so pick whichever you find easier to read.
When should I use a lambda instead of def?
Use a lambda when you pass a short one-off function, like a sorted() key. Use def when you’ll reuse or document it.
Where is the lambda expression documented?
See lambda expressions in the official Python language reference.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn