Skip to content
Laviyx Learn

Try

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.

Intermediate6 min readUpdated
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#

Python
lambda parameters: expression

A lambda takes any number of parameters and returns the value of one expression. There is no return keyword and no block of statements.

Python
square = lambda n: n * n
print(square(5))

add = lambda a, b: a + b
print(add(2, 3))
Output
25
5

These 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:

Python
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])
Output
[('Ravi', 85), ('Asha', 92), ('Meera', 97)]
('Meera', 97)

lambda s: s[1] says "compare students by their score".

With dictionaries:

Python
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"])])
Output
Pen
['Pen', 'Chair', 'Laptop']

You do not always need a lambda; an existing function works too:

Python
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))
Output
['Kiwi', 'apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'Kiwi']
['Kiwi', 'apple', 'banana', 'cherry']
banana

Sorting 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):

Python
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)
Output
('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:

Python
grade = lambda s: "pass" if s >= 40 else "fail"
print(grade(55), grade(30))
Output
pass fail

map and filter#

map() applies a function to every item; filter() keeps items for which a function returns true:

Python
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
Output
[10, 20, 30, 40, 50, 60]
[2, 4, 6]

In modern Python, list comprehensions usually express the same thing more clearly:

Python
print([n * 10 for n in nums], [n for n in nums if n % 2 == 0])
Output
[10, 20, 30, 40, 50, 60] [2, 4, 6]

Lambda or def?#

Use a lambda when…Use def when…
it is short and used once, right where it is writtenit is reused
it is a key for sorting, min or maxit needs several statements
it fits comfortably on one lineit deserves a name and a docstring

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.

Python
people = [("Asha", "Pune", 21), ("Ravi", "Delhi", 25),
          ("Meera", "Pune", 19), ("John", "Delhi", 30)]
Show hint

key=lambda p: (p[1], -p[2]).

Show solution
Python
for p in sorted(people, key=lambda p: (p[1], -p[2])):
    print(p)
Output
('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?