Python course menu
Python Lambda Functions: Short Anonymous Functions With Examples
Learn Python lambda functions: syntax, when to use them, sorting with key=lambda, max and min by a field, map and filter, comparing lambdas with list comprehensions, and when a normal def is better.
On this page
A lambda is a small, one-line function without a name. It is written exactly where it is needed, most often to tell sorted(), max() or min() how to compare items.
Syntax#
lambda parameters: expressionA lambda takes any number of parameters and returns the value of one expression. There is no return keyword and no block of statements.
square = lambda n: n * n
print(square(5))
add = lambda a, b: a + b
print(add(2, 3))25
5These are equivalent to small def functions. Assigning a lambda to a name like this works, but it is not how lambdas are usually used, and the PEP 8 style guide recommends def when you need a named function.
The main use: sorting with key#
sorted(), min() and max() accept a key function that turns each item into the value to compare. A lambda is perfect for that:
students = [("Asha", 92), ("Ravi", 85), ("Meera", 97)]
print(sorted(students, key=lambda s: s[1]))
print(sorted(students, key=lambda s: s[1], reverse=True)[0])[('Ravi', 85), ('Asha', 92), ('Meera', 97)]
('Meera', 97)lambda s: s[1] says "compare students by their score".
With dictionaries:
products = [
{"name": "Laptop", "price": 55000},
{"name": "Pen", "price": 20},
{"name": "Chair", "price": 7000},
]
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"])
print([p["name"] for p in sorted(products, key=lambda p: p["price"])])Pen
['Pen', 'Chair', 'Laptop']You do not always need a lambda; an existing function works too:
words = ["banana", "Kiwi", "apple", "cherry"]
print(sorted(words)) # uppercase sorts before lowercase
print(sorted(words, key=str.lower)) # case-insensitive
print(sorted(words, key=len)) # by length
print(max(words, key=len))['Kiwi', 'apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'Kiwi']
['Kiwi', 'apple', 'banana', 'cherry']
bananaSorting by several things#
Return a tuple to sort by more than one value. Here: by city A to Z, then by age oldest first (negating a number reverses its order):
people = [("Asha", "Pune", 21), ("Ravi", "Delhi", 25),
("Meera", "Pune", 19), ("John", "Delhi", 30)]
for p in sorted(people, key=lambda p: (p[1], -p[2])):
print(p)('John', 'Delhi', 30)
('Ravi', 'Delhi', 25)
('Asha', 'Pune', 21)
('Meera', 'Pune', 19)Conditional expressions in a lambda#
A lambda can contain a one-line if/else:
grade = lambda s: "pass" if s >= 40 else "fail"
print(grade(55), grade(30))pass failmap and filter#
map() applies a function to every item; filter() keeps items for which a function returns true:
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))[10, 20, 30, 40, 50, 60]
[2, 4, 6]In modern Python, list comprehensions usually express the same thing more clearly:
print([n * 10 for n in nums], [n for n in nums if n % 2 == 0])[10, 20, 30, 40, 50, 60] [2, 4, 6]Lambda or def?#
Common mistakes#
Practice#
Practice exercise
Sort this list of people by city, and within each city by age, oldest first. Print one person per line.
people = [("Asha", "Pune", 21), ("Ravi", "Delhi", 25),
("Meera", "Pune", 19), ("John", "Delhi", 30)]Show hint
key=lambda p: (p[1], -p[2]).
Show solution
for p in sorted(people, key=lambda p: (p[1], -p[2])):
print(p)('John', 'Delhi', 30)
('Ravi', 'Delhi', 25)
('Asha', 'Pune', 21)
('Meera', 'Pune', 19)The tuple (city, -age) sorts by city first; for the same city, the negative age puts older people first.
Key takeaway#
Finished this lesson?