The lambda keyword lets you build a throw-away function on the spot, right inside the line that needs it. It shines when another function asks you for a short rule just once, for example the rule that decides how a list is sorted. This lesson covers lambda syntax, using lambdas with map, filter and reduce, and sorting with the key argument, which is where lambdas appear most often in real code.
In this lesson you will learn
- The
lambda arguments: expressionsyntax - How a lambda compares with a
deffunction map,filterandfunctools.reduce- Sorting with
sorted(..., key=...)andreverse=True - Using
keywithmaxandmin
You should already know how to write Python functions.
Lambda Syntax, map, filter and reduce
square = lambda x: x * x
add = lambda a, b: a + b
print(square(7), add(3, 4))
# The same function written with def
def square_def(x):
return x * x
print(square_def(7) == square(7))
nums = [4, 11, 8, 3, 15, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))
# A comprehension is often clearer than map/filter
print([n * 10 for n in nums if n % 2 == 0])
Output
49 7
True
[40, 110, 80, 30, 150, 60]
[4, 8, 6]
120
[40, 80, 60]
lambda x: x * xtakes one argument and returnsx * x. The body must be a single expression, and its value is returned automatically; there is noreturnkeyword.- A lambda is exactly equivalent to a small
deffunction. Assigning a lambda to a name, as withsquarehere, works but is discouraged by the PEP 8 style guide; usedefwhen a function needs a name. map(fn, items)applies a function to every item.filter(fn, items)keeps items for which the function returns true. Both return lazy iterators, solist()is used to see the results.reduce, fromfunctools, combines the items pairwise into one value: ((((1×2)×3)×4)×5) = 120.- A list comprehension often does the same job as
mapandfilterand is usually easier to read.
Sorting With key
students = [
("Nusrat", "CSE", 3.82),
("Arif", "EEE", 3.41),
("Tania", "CSE", 3.95),
("Rafi", "EEE", 2.98),
]
by_cgpa = sorted(students, key=lambda s: s[2], reverse=True)
for name, dept, cgpa in by_cgpa:
print(f"{name:7} {cgpa}")
# Sort by department, then by CGPA (highest first) inside each department
by_dept = sorted(students, key=lambda s: (s[1], -s[2]))
print([s[0] for s in by_dept])
words = ["banana", "Cherry", "apple", "Date"]
print(sorted(words)) # capital letters sort first
print(sorted(words, key=str.lower)) # case-insensitive
print(max(words, key=len), min(words, key=len))
prices = {"pen": 20, "bag": 950, "book": 300}
print(sorted(prices.items(), key=lambda kv: kv[1]))
Output
Tania 3.95
Nusrat 3.82
Arif 3.41
Rafi 2.98
['Tania', 'Nusrat', 'Arif', 'Rafi']
['Cherry', 'Date', 'apple', 'banana']
['apple', 'banana', 'Cherry', 'Date']
banana Date
[('pen', 20), ('book', 300), ('bag', 950)]
sorted(items, key=fn)callsfnon each item and sorts by the results.key=lambda s: s[2]sorts students by their CGPA, the third field.reverse=Truesorts from largest to smallest.- A key can return a tuple to sort by several fields:
(s[1], -s[2])sorts by department, then by CGPA descending (the minus sign reverses the numeric order). - Plain
sorted(words)puts capital letters before lowercase ones because it compares character codes.key=str.lowergives a case-insensitive order; an existing function can be passed directly without a lambda. maxandminacceptkeytoo. When two items tie, as “banana” and “Cherry” do on length, the first one wins.dict.items()gives (key, value) pairs, sokey=lambda kv: kv[1]sorts a dictionary by its values.list.sort()sorts a list in place;sorted()returns a new list and works on any iterable. Python’s sort is stable: items with equal keys keep their original order.
lambda vs def
lambda | def | |
|---|---|---|
| Name | Anonymous | Named |
| Body | One expression | Any number of statements |
| Return | Automatic | Uses return |
| Docstring and type hints | No | Yes |
| Best for | Short throw-away logic passed to another function | Everything else |
Common Mistakes
- Writing statements in a lambda, such as an assignment or
ifblock; only expressions are allowed. A conditional expression works:lambda n: "even" if n % 2 == 0 else "odd". - Forgetting
list()aroundmaporfilterand printing a map object. - Lambdas in a loop that all use the loop variable’s final value:
[lambda: i for i in range(3)]all return 2. Bind it with a default:lambda i=i: i. - Squeezing complex logic into one lambda; a named function is clearer and easier to test.
Practice Exercises
Exercise 1. Sort the list ["kiwi", "fig", "banana", "apple"] by word length, shortest first.
Show answer
print(sorted(["kiwi", "fig", "banana", "apple"], key=len))
# ['fig', 'kiwi', 'apple', 'banana']
Exercise 2. Use filter and a lambda to keep only the names that start with a vowel.
Show answer
names = ["Arif", "Nadia", "Imran", "Rafi", "Omar"]
print(list(filter(lambda n: n[0].lower() in "aeiou", names)))
# ['Arif', 'Imran', 'Omar']
Frequently Asked Questions
Why is it called lambda?
The name comes from lambda calculus, a mathematical system for describing functions created by Alonzo Church in the 1930s. Many languages use the word for anonymous functions.
Can a lambda take no arguments or several?
Yes. lambda: 42 takes none, and lambda a, b, c=0: a + b + c takes several, including defaults.
Summary
lambda args: expressioncreates a small anonymous function.- Pass lambdas to
sorted,max,min,mapandfilter. - Sort by several fields with a tuple key; use
reverse=Truefor descending. - Prefer
deffor anything longer than one simple expression.
Next: Python *args and **kwargs.
