Skip to content
Python

Python Lambda Functions: sorted() with key, map() and filter()

Ihsan Ullah · 12 min read
Python lambda, Lesson 25 of the Python course: sorted() with key, map() and filter()

Python course · Module 5: Functions · Lesson 25 of 63

Quick answer: A lambda is a small function without a name, written in one line: lambda price: price + 150 does the same as a def that returns price + 150. Its body must be a single expression. Lambdas are most useful as the key of sorted(): sorted(products, key=lambda p: p[1]) sorts a list of tuples by the second item, and reverse=True sorts from largest to smallest. map() and filter() also take a function, but a list comprehension is usually easier to read.

In this lesson you will learn:

  • how to write a lambda, and what it cannot do
  • how sorted(key=...) sorts strings, tuples and dictionaries, and how reverse=True works
  • how to sort a dictionary by its values
  • how map() and filter() work, and when a comprehension is better
  • how operator.itemgetter() can replace a simple lambda

Before you start: finish Lesson 24, Python Variable Scope: LEGB, global and nonlocal. You also need sort() and sorted() from Lesson 15, keyword arguments from Lesson 23 and comprehensions from Lesson 21. All examples were tested on Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

Lambda syntax

A lambda has the keyword lambda, then the parameters, a colon and one expression. The value of the expression is returned automatically; you do not write return. Here is a def from Lesson 22 and the same function as a lambda:

def add_delivery(price):
    return price + 150

add_delivery_short = lambda price: price + 150

print(add_delivery(450))
print(add_delivery_short(450))
print((lambda price, qty: price * qty)(60, 3))
print(add_delivery.__name__, add_delivery_short.__name__)
600
600
180
add_delivery <lambda>
  • Both versions give 600. A lambda is just a shorter way to write a small function.
  • A lambda can take several parameters, like price, qty. The third line makes a lambda and calls it at once with (60, 3).
  • Every function knows its name. The def function is called add_delivery, but the lambda is only <lambda>, even though we stored it in a variable.

That last point is why PEP 8, Python’s style guide, says: “Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.” A name like <lambda> in an error message tells you nothing. So do not write name = lambda ...; use def. Use a lambda only where you pass a small function straight into another function, as in the rest of this lesson.

What a lambda cannot do

The Python tutorial says lambdas “are syntactically restricted to a single expression”. You cannot use return, an assignment, a loop or several lines inside one:

add_delivery = lambda price: return price + 150
  File "/home/learner/python-course/err1_lambda_return.py", line 1
    add_delivery = lambda price: return price + 150
                                 ^^^^^^
SyntaxError: invalid syntax

An if statement is not allowed either, but a conditional expression is, because it is an expression:

label = lambda price: "cheap" if price < 100 else "expensive"
print(label(60))
print(label(3200))
cheap
expensive

If you need more than this, write a normal def function.

Sorting with key=

In Lesson 15 you saw that sorted() puts capital letters before small letters. The key argument fixes that. key takes a function. Python calls it once for each item and sorts the items by the values it returns, not by the items themselves:

names = ["pen", "Notebook", "backpack", "Ruler"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(sorted(names, key=len))
['Notebook', 'Ruler', 'backpack', 'pen']
['backpack', 'Notebook', 'pen', 'Ruler']
['pen', 'Ruler', 'Notebook', 'backpack']
  • key=str.lower compares the lower-case version of each word, so 'backpack' comes first. The words in the result keep their original case.
  • key=len sorts by length: 3, 5, 8 and 8 letters.
  • Write the function name without brackets: key=str.lower, not key=str.lower(). You give sorted() the function, and it calls the function itself.

The Sorting HOW TO explains that the key function “is called exactly once for each input record”. The same key= works with list.sort().

Sorting a list of tuples

Our shop keeps each product as a tuple of name, price and stock (Lesson 16). Without a key, tuples are compared item by item, starting with the first, so they are sorted by name. To sort by price, give a lambda that returns the price:

products = [("Notebook", 450, 12), ("Pen", 60, 40), ("Backpack", 3200, 5), ("Ruler", 40, 30)]
print(sorted(products))

by_price = sorted(products, key=lambda product: product[1])
for name, price, stock in by_price:
    print(f"{name:<10}{price:>6}")
[('Backpack', 3200, 5), ('Notebook', 450, 12), ('Pen', 60, 40), ('Ruler', 40, 30)]
Ruler         40
Pen           60
Notebook     450
Backpack    3200

lambda product: product[1] takes one tuple and returns its price. This is exactly the kind of small, one-time function a lambda is for.

Largest first with reverse=True

reverse=True turns the order around, so the largest key comes first:

products = [("Notebook", 450, 12), ("Pen", 60, 40), ("Backpack", 3200, 5), ("Ruler", 40, 30)]

dearest_first = sorted(products, key=lambda product: product[1], reverse=True)
print([name for name, price, stock in dearest_first])

most_stock = sorted(products, key=lambda product: product[2], reverse=True)
print([name for name, price, stock in most_stock])
['Backpack', 'Notebook', 'Pen', 'Ruler']
['Pen', 'Ruler', 'Notebook', 'Backpack']

Both key and reverse must be given by name. sorted(names, str.lower) fails with TypeError: sorted expected 1 argument, got 2.

Ties and sorting by two things

What happens when two items have the same key? Here a pen and a marker both cost 60:

items = [("Pen", 60), ("Eraser", 25), ("Marker", 60), ("Ruler", 40)]
print(sorted(items, key=lambda item: item[1]))
print(sorted(items, key=lambda item: (item[1], item[0])))
print(sorted(items, key=lambda item: (-item[1], item[0])))
[('Eraser', 25), ('Ruler', 40), ('Pen', 60), ('Marker', 60)]
[('Eraser', 25), ('Ruler', 40), ('Marker', 60), ('Pen', 60)]
[('Marker', 60), ('Pen', 60), ('Ruler', 40), ('Eraser', 25)]
  • In the first line, Pen stays before Marker, as in the original list. Python’s sort is stable: the built-in functions page says a stable sort “guarantees not to change the relative order of elements that compare equal”.
  • To break ties, return a tuple: (price, name) sorts by price, then by name.
  • The minus sign in -item[1] sorts the prices from highest to lowest while the names still go A to Z. This trick only works for numbers.

Sorting a list of dictionaries

For a list of dictionaries (Lesson 17), the lambda returns one value from each dictionary:

orders = [
    {"customer": "Sara", "total": 1250},
    {"customer": "Ali", "total": 600},
    {"customer": "Hina", "total": 3200},
]
for order in sorted(orders, key=lambda order: order["total"], reverse=True):
    print(order["customer"], order["total"])
Hina 3200
Sara 1250
Ali 600

Without a key, Python does not know how to compare two dictionaries:

orders = [
    {"customer": "Sara", "total": 1250},
    {"customer": "Ali", "total": 600},
]
print(sorted(orders))
Traceback (most recent call last):
  File "/home/learner/python-course/err2_sort_dicts_no_key.py", line 5, in <module>
    print(sorted(orders))
          ~~~~~~^^^^^^^^
TypeError: '<' not supported between instances of 'dict' and 'dict'

Sorting a dictionary by value

sorted() on a dictionary sorts its keys. To sort by the values, sort the items() pairs and use the second part of each pair as the key:

stock = {"Notebook": 12, "Pen": 40, "Backpack": 5, "Ruler": 30}
pairs = sorted(stock.items(), key=lambda pair: pair[1])
print(pairs)
print(dict(pairs))
print(sorted(stock, key=stock.get, reverse=True))
[('Backpack', 5), ('Notebook', 12), ('Ruler', 30), ('Pen', 40)]
{'Backpack': 5, 'Notebook': 12, 'Ruler': 30, 'Pen': 40}
['Pen', 'Ruler', 'Notebook', 'Backpack']

The result is a list of (name, count) tuples, lowest stock first. dict(pairs) turns it back into a dictionary, which keeps that order. The last line passes the dictionary’s own get method as the key, so the product names are sorted by their stock, highest first.

operator.itemgetter()

Lambdas like lambda product: product[1] are so common that the standard library has a ready-made tool for them. itemgetter(1) from the operator module makes a function that returns item 1 of whatever you give it. The from operator import itemgetter line loads it; Lesson 27 explains imports.

from operator import itemgetter

products = [("Notebook", 450, 12), ("Pen", 60, 40), ("Backpack", 3200, 5), ("Ruler", 40, 30)]
orders = [{"customer": "Sara", "total": 1250}, {"customer": "Ali", "total": 600}]

get_price = itemgetter(1)
print(get_price(("Pen", 60, 40)))
print(sorted(products, key=itemgetter(1)))
print(sorted(orders, key=itemgetter("total")))
print(itemgetter(0, 1)(("Pen", 60, 40)))
60
[('Ruler', 40, 30), ('Pen', 60, 40), ('Notebook', 450, 12), ('Backpack', 3200, 5)]
[{'customer': 'Ali', 'total': 600}, {'customer': 'Sara', 'total': 1250}]
('Pen', 60)

itemgetter(1) works like lambda product: product[1], and itemgetter("total") like lambda order: order["total"]. With several items, it returns a tuple. The operator docs show the same idea: after f = itemgetter(2), f(r) returns r[2]. Use whichever you find clearer.

map() and filter()

map(function, items) calls the function on every item. filter(function, items) keeps only the items for which the function returns a true value. Both give back an iterator, a lazy object that makes its values one at a time, so wrap it in list() to see them:

prices = [450, 60, 3200, 40]
as_text = map(str, prices)
print(type(as_text))
print(list(as_text))
print(", ".join(map(str, prices)))
print(list(map(lambda price: price + 150, prices)))
print(list(map(int, "12 40 5".split())))
<class 'map'>
['450', '60', '3200', '40']
450, 60, 3200, 40
[600, 210, 3350, 190]
[12, 40, 5]

map(str, prices) solves the join() problem from Lesson 20: join() needs strings, so we turn each number into a string first. map(int, ...) does the opposite and turns typed text into numbers.

filter() with a lambda keeps the cheap items. Notice what happens when we use the same iterator twice:

prices = [450, 60, 3200, 40]
cheap = filter(lambda price: price < 100, prices)
print(list(cheap))
print(list(cheap))
[60, 40]
[]

An iterator can be used only once. The first list() took all the values, so the second one gets nothing. If you need the result more than once, store it as a list: cheap = list(filter(...)).

map and filter vs list comprehensions

Every map() and filter() above can also be written as a comprehension:

prices = [450, 60, 3200, 40]

print(list(map(lambda price: price + 150, prices)))
print([price + 150 for price in prices])

print(list(filter(lambda price: price < 100, prices)))
print([price for price in prices if price < 100])

print(list(map(lambda price: price + 150, filter(lambda price: price < 100, prices))))
print([price + 150 for price in prices if price < 100])
[600, 210, 3350, 190]
[600, 210, 3350, 190]
[60, 40]
[60, 40]
[210, 190]
[210, 190]

The results are the same. When you would need a lambda, the comprehension is shorter and reads from left to right. Compare the last two lines: map() inside filter() is hard to follow. The Python tutorial shows list(map(lambda x: x2, range(10))) next to [x2 for x in range(10)] and calls the comprehension “more concise and readable”.

map() is still a good choice when the function already exists and has a name, as in map(str, prices) or map(int, text.split()).

Try it yourself

Exercise 1: Rank the students

students = [("Ali", 72), ("Sara", 91), ("Hina", 85), ("Usman", 64)]. Print each name and mark, highest mark first.

Exercise 2: Low stock first

stock = {"Notebook": 12, "Pen": 40, "Backpack": 5, "Ruler": 30}. Print each product and its stock as Backpack: 5, starting with the lowest stock.

Exercise 3: Rewrite map and filter

Write list(map(str.upper, filter(lambda word: len(word) > 3, words))) as a list comprehension, for words = ["pen", "notebook", "ruler", "backpack"], and check that both give the same list.

Solutions

Solution 1

students = [("Ali", 72), ("Sara", 91), ("Hina", 85), ("Usman", 64)]
ranking = sorted(students, key=lambda student: student[1], reverse=True)
for name, marks in ranking:
    print(name, marks)
Sara 91
Hina 85
Ali 72
Usman 64

The lambda returns the mark, and reverse=True puts the highest mark first.

Solution 2

stock = {"Notebook": 12, "Pen": 40, "Backpack": 5, "Ruler": 30}
for name, count in sorted(stock.items(), key=lambda pair: pair[1]):
    print(f"{name}: {count}")
Backpack: 5
Notebook: 12
Ruler: 30
Pen: 40

Sorting items() by pair[1] sorts the products by their stock value.

Solution 3

words = ["pen", "notebook", "ruler", "backpack"]
print(list(map(str.upper, filter(lambda word: len(word) > 3, words))))
print([word.upper() for word in words if len(word) > 3])
['NOTEBOOK', 'RULER', 'BACKPACK']
['NOTEBOOK', 'RULER', 'BACKPACK']

The if part of the comprehension does the filtering, and word.upper() does the mapping.

Common mistakes

  • Calling the key function. sorted(names, key=str.lower()) gives TypeError: unbound method str.lower() needs an argument. Pass the function without brackets: key=str.lower.
  • Sorting dictionaries without a key. sorted(orders) gives TypeError: '<' not supported between instances of 'dict' and 'dict'. Add key=lambda order: order["total"].
  • Writing return in a lambda. lambda price: return price + 150 gives SyntaxError: invalid syntax. The expression after the colon is returned automatically.
  • Using a map or filter result twice. The second list(cheap) gives [], because an iterator can only be used once. Store list(...) in a variable.
  • Giving a lambda a name. add_delivery = lambda price: price + 150 works, but PEP 8 says to use def, which gives the function a real name.

Frequently asked questions

How do I sort a list of dictionaries by a value in Python?

Pass a key that returns that value: sorted(orders, key=lambda order: order["total"]). Add reverse=True for the largest first. operator.itemgetter("total") does the same job as the lambda.

What is the difference between map() and a list comprehension?

Both apply something to every item. map() takes a function and returns an iterator that can be used once, while a comprehension builds a list directly. Use map() with an existing function like str or int; use a comprehension when you would otherwise need a lambda.

Can a Python lambda have multiple lines or statements?

No. A lambda body is a single expression, so return, assignments, loops and if statements are not allowed. A conditional expression like "cheap" if price < 100 else "expensive" is fine. For anything longer, write a def function.

Summary

  • lambda params: expression makes a small unnamed function; use it inline, and use def when you want a name.
  • sorted(items, key=function) sorts by the value the function returns; pass the function without brackets.
  • reverse=True sorts from largest to smallest, and a tuple key like (price, name) breaks ties.
  • Sort a dictionary by value with sorted(d.items(), key=lambda pair: pair[1]); operator.itemgetter() can replace simple lambdas.
  • map() and filter() return one-time iterators; a comprehension is usually clearer when you would need a lambda.

Next lesson

Next: Lesson 26, Python Recursion: Base Case, Call Stack and RecursionError.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *