Python Tutorial › Functions › Lambda

Python Lambda

IntermediateLesson 25 of 478 min read10 runnable examples

A lambda is a small function written in a single expression, without a name. You will mostly use lambdas as short “key” or “rule” functions passed to sorted(), max(), map() and filter().

Advertisement
In this lesson
  • Write a lambda expression
  • Sort data with a lambda key
  • Transform and filter with map() and filter()
  • Know when a normal def is better

Lambda syntax

lambda parameters: expression. The expression’s value is returned automatically; there is no return keyword.

Python
square = lambda x: x * xadd = lambda a, b: a + b print(square(6), add(2, 3))
Output
36 5

The two lines above are equivalent to:

Python
def square(x):    return x * x print(square(6))
Output
36
Note

Assigning a lambda to a name, as in the first example, works but PEP 8 recommends def for that. Lambdas are meant to be used inline, where a function is needed only once.

Sort with a lambda key

key tells sorted() what to compare. The lambda receives each item and returns the value to sort by.

Python
employees = [("Asha", 52000), ("Ravi", 61000), ("Meena", 48000)] by_salary = sorted(employees, key=lambda e: e[1])print(by_salary) by_name_desc = sorted(employees, key=lambda e: e[0], reverse=True)print([name for name, _ in by_name_desc])
Output
[('Meena', 48000), ('Asha', 52000), ('Ravi', 61000)]
['Ravi', 'Meena', 'Asha']

Sort dictionaries, or sort by several things at once by returning a tuple:

Python
users = [{"name": "ravi", "age": 31}, {"name": "asha", "age": 28}, {"name": "meena", "age": 31}]print([u["name"] for u in sorted(users, key=lambda u: (-u["age"], u["name"]))])
Output
['meena', 'ravi', 'asha']

max() and min() with a key

Python
words = ["python", "is", "readable"]print(max(words, key=lambda w: len(w))) prices = {"pen": 10, "bag": 650, "book": 120}print(min(prices, key=lambda k: prices[k]))
Output
readable
pen

map(): transform every item

map(function, iterable) applies the function to each item and returns an iterator. Wrap it in list() to see the results.

Python
celsius = [0, 25, 37.5, 100]fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))print(fahrenheit) print(list(map(str.upper, ["get", "post"])))   # any function works, not just lambdas
Output
[32.0, 77.0, 99.5, 212.0]
['GET', 'POST']

filter(): keep matching items

filter(function, iterable) keeps the items for which the function returns a truthy value.

Python
scores = [45, 82, 67, 91, 38]print(list(filter(lambda s: s >= 50, scores)))
Output
[82, 67, 91]
Tip

A list comprehension is often clearer than map or filter with a lambda: [c * 9 / 5 + 32 for c in celsius] and [s for s in scores if s >= 50] do the same jobs. Use whichever reads better.

Lambdas with default values

Python
apply_discount = lambda price, pct=10: round(price * (1 - pct / 100), 2)print(apply_discount(500), apply_discount(500, 25))
Output
450.0 375.0

Limits of lambda

A lambda can contain only one expression: no statements, no if blocks (a conditional expression is fine), no loops, no assignments.

Python
grade = lambda m: "pass" if m >= 50 else "fail"print(grade(72), grade(31))
Output
pass fail
Python
bad = lambda x: y = x + 1
Output
  File "main.py", line 1
    bad = lambda x: y = x + 1
          ^^^^^^^^^^^
SyntaxError: cannot assign to lambda

If the logic needs more than one line, write a normal def.

Check your understanding

Predict the output

pairs = [(1, "b"), (3, "a"), (2, "c")]print(sorted(pairs, key=lambda p: p[1]), list(map(lambda p: p[0] * 10, pairs)))

Quick quiz

1. What does (lambda x, y: x * y)(3, 4) return?

2. Which is NOT allowed in a lambda?

3. What does map() return in Python 3?

Exercise: sort products

Sort the products by price, cheapest first, then print the names of products costing more than 100 using filter.

Input
[("pen", 10), ("bag", 650), ("book", 120), ("tape", 35)]
Expected output
[('pen', 10), ('tape', 35), ('book', 120), ('bag', 650)]
['bag', 'book']
Hint 1

key=lambda p: p[1] sorts by price.

Program Practice

Python lambda FAQ

What is a lambda function in Python?

A lambda is an anonymous function written as a single expression: lambda x: x * 2. It is used for short functions passed to other functions.

Can a lambda have multiple lines?

No. A lambda holds exactly one expression. Use def for anything longer.

When should I use lambda instead of def?

Use a lambda for a short throwaway function passed as an argument, such as a key for sorted(). Use def when the function is reused, needs a name, or has more than one step.

Leave a Comment