Python Lambda Functions: Syntax and Examples - Python with AI tutorial chapter 21
Python

Python Lambda Functions: Syntax, Examples and When to Use

Python with AI Tutorial · Chapter 21 of 48

A Python lambda function is a small anonymous function written in a single expression. It has no name and no def block, just the keyword lambda, its parameters, a colon and the value to return. Lambdas are most useful as short throwaway functions passed to sorted(), map(), filter() and similar tools.

Lambda syntax

The general form is lambda parameters: expression. The expression is evaluated and returned automatically; you never write return. A lambda can take any number of parameters but can contain only one expression, not statements such as loops or assignments.

add_tax = lambda price: price * 1.18
print(add_tax(100))
print(add_tax(250))
Output:
118.0
295.0

Assigning a lambda to a name like this works, but it is not recommended in real code. If the function deserves a name, write it with def so tracebacks and documentation show that name. The lambda form shines when the function is used once, in place.

Lambda versus def

These two definitions behave identically when called. The difference is style and where each fits.

def margin_def(revenue, cost):
    return (revenue - cost) / revenue

margin_lambda = lambda revenue, cost: (revenue - cost) / revenue

print(margin_def(5000, 3500))
print(margin_lambda(5000, 3500))
print(margin_def.__name__, margin_lambda.__name__)
Output:
0.3
0.3
margin_def <lambda>
Feature def function lambda
Name Yes Anonymous (shows as <lambda>)
Body Any number of statements One expression only
Docstring and type hints Supported Not supported
Return Explicit return Implicit
Best for Anything reused or longer than a line Short one-off callbacks

Sorting with a lambda key

The most common use of lambda is the key argument of sorted() and list.sort(). The key function tells Python which value to sort by. Here we sort a list of employee tuples by salary instead of by name.

employees = [("Asha", 72000), ("Ben", 58000), ("Chloe", 91000)]
by_salary = sorted(employees, key=lambda emp: emp[1], reverse=True)
for name, salary in by_salary:
    print(f"{name:<6} {salary:,}")
Output:
Chloe  91,000
Asha   72,000
Ben    58,000

Without the key, Python would compare the tuples element by element and sort alphabetically by name. The lambda redirects the comparison to the second element.

Sorting dictionaries

Lists of dictionaries are everywhere in business data, whether from a JSON API or a CSV reader. A lambda picks the field to sort by in one line.

orders = [
    {"id": 101, "customer": "Delta Ltd", "amount": 4200},
    {"id": 102, "customer": "Acme Co", "amount": 15500},
    {"id": 103, "customer": "Beta Inc", "amount": 800},
]
for o in sorted(orders, key=lambda o: o["amount"]):
    print(o["id"], o["customer"], o["amount"])
Output:
103 Beta Inc 800
101 Delta Ltd 4200
102 Acme Co 15500
Try it with AI

Ask the assistant for a multi-level sort key and to explain how a tuple returned from a lambda controls the ordering.

I have a Python list of dictionaries with keys "region", "rep" and "sales". Write a sorted() call with a lambda key that sorts by region A-Z and then by sales highest first within each region. Explain how returning a tuple from the lambda and using a negative number achieves the mixed ordering.

map() and filter()

map() applies a function to every item and filter() keeps only the items for which the function returns True. Both return lazy iterators, so wrap them in list() to see the results.

prices_usd = [120, 45, 300, 15]
prices_inr = list(map(lambda p: round(p * 83.5), prices_usd))
print(prices_inr)

big_ticket = list(filter(lambda p: p > 100, prices_usd))
print(big_ticket)
Output:
[10020, 3758, 25050, 1252]
[120, 300]

Many Python developers prefer list comprehensions for these tasks: [round(p * 83.5) for p in prices_usd] reads more naturally to most people. Both approaches are correct, so use the one your team finds clearer.

Conditional expression inside a lambda

A lambda cannot contain an if statement, but it can use the one-line conditional expression a if condition else b, which is an expression rather than a statement.

grade = lambda score: "Pass" if score >= 60 else "Fail"
results = [88, 42, 60, 59]
print([grade(s) for s in results])
Output:
['Pass', 'Fail', 'Pass', 'Fail']

Returning a lambda from a function

Because a lambda is an ordinary function object, another function can build and return one. This lets you manufacture a family of similar functions from a single template, a pattern often called a function factory.

def make_multiplier(factor):
    return lambda x: x * factor

double = make_multiplier(2)
add_gst = make_multiplier(1.18)
print(double(450))
print(add_gst(1000))
Output:
900
1180.0

Each returned lambda remembers the factor it was created with. The next chapter on scope explains why this works; the short version is that the inner function keeps a reference to the variables of the function that created it.

Common mistake: stuffing too much into a lambda. If you need nested conditionals, several calculations or a comment to explain it, the expression has outgrown lambda. Convert it to a def with a descriptive name; the extra lines are worth it.

Using lambda with max() and min()

max() and min() also accept a key argument. Instead of sorting the whole list to find the top item, ask for the maximum by a field directly.

products = {"Chair": 1450, "Desk": 3900, "Lamp": 620}
best = max(products, key=lambda name: products[name])
cheapest = min(products.items(), key=lambda kv: kv[1])
print(best)
print(cheapest)
Output:
Desk
('Lamp', 620)
Try it with AI

Give the assistant a lambda you find hard to read and ask for a named function plus an explanation of when each form is preferable.

This Python lambda is hard to read: key=lambda r: (r["status"] != "Paid", -r["days_overdue"], r["customer"].lower()). Rewrite it as a def function with a docstring and comments, explain in plain English what sort order it produces for a list of invoices, and tell me whether you would keep the lambda or the def in a production report.

Common mistakes

  • Writing return inside a lambda; the expression value is returned automatically.
  • Trying to put a loop, assignment or multi-line logic in a lambda.
  • Assigning lambdas to names throughout a module instead of using def.
  • Forgetting that map() and filter() return iterators, so printing them shows an object address, not the values.
  • Using a lambda where a built-in already exists, for example key=lambda s: s.lower() can be key=str.lower.

Exercise

Given invoices = [("INV-7", 30), ("INV-2", 5), ("INV-9", 65), ("INV-4", 0)] where the second value is days overdue, use a lambda to sort the list from most overdue to least, then use filter() with a lambda to build a list of only the invoices overdue by more than 14 days.

Show answer
invoices = [("INV-7", 30), ("INV-2", 5), ("INV-9", 65), ("INV-4", 0)]
by_overdue = sorted(invoices, key=lambda inv: inv[1], reverse=True)
print(by_overdue)
late = list(filter(lambda inv: inv[1] > 14, invoices))
print(late)
Output:
[('INV-9', 65), ('INV-7', 30), ('INV-2', 5), ('INV-4', 0)]
[('INV-7', 30), ('INV-9', 65)]

Related chapters

FAQ

What is a lambda function in Python?

A lambda is an anonymous one-expression function written as lambda parameters: expression. It returns the value of the expression and is usually passed directly to functions such as sorted(), map() or filter().

When should I use lambda instead of def in Python?

Use lambda for a short function that is used once, typically as a key argument. Use def whenever the function needs a name, a docstring, several statements or will be reused.

Can a Python lambda have multiple lines or statements?

No. A lambda body must be a single expression. It can use a conditional expression like a if x else b, but not if blocks, loops or assignments.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 21 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com