TetSharing
Python tutorial · 22 chapters
  1. Get started
  2. Syntax and comments
  3. Variables
  4. Numbers and math
  5. Strings
  6. f-strings and formatting
  7. Booleans and logic
  8. if, elif, else
  9. Lists
  10. Tuples
  11. Dictionaries
  12. Sets
  13. for loops and range()
  14. while, break, continue
  15. Functions
  16. Default and keyword arguments
  17. Lambda and sorting keys
  18. List comprehensions
  19. Errors and exceptions
  20. Modules and imports
  21. Reading and writing files
  22. Classes and objects

Final Python quiz
Cheat sheet: python string methods
Cheat sheet: python lists dicts

Chapter 17 of 22 · By Ethan Cole · Updated November 21, 2026

Python Lambda Functions and Sorting With key=

A lambda is a tiny function written as an expression: lambda x: x * x takes one argument and returns its square. It has no name and no return keyword; the single expression after the colon is the return value. Lambdas are most useful as short throwaway arguments to other functions.

Lambda versus def

square = lambda x: x * x works, but style guides discourage assigning a lambda to a name, because def square(x): return x * x is just as short, gets a proper name in error messages, and can hold a docstring. Use a lambda only when the function is passed directly to something else and is too small to deserve a name.

Key functions

sorted(), list.sort(), min() and max() accept a key argument: a function that is called on each item to produce the value actually compared. The items themselves are returned unchanged.

  • key=str.lower sorts text case-insensitively. Notice in the example that plain sorted() puts "Fig" first, because uppercase letters have smaller character codes than lowercase ones.
  • key=len sorts by length. Python's sort is stable: items with equal keys keep their original order.
  • key=lambda w: w[-1] sorts by the last letter.
  • key=lambda b: b[1] picks the second field of each tuple, so min() finds the cheapest book.
Python 3 · editable

Expected output

49
['Fig', 'apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'Fig']
['Fig', 'apple', 'banana', 'cherry']
['banana', 'apple', 'Fig', 'cherry']
Paper Cranes
[22.0, 34.5, 25.0]

To sort by several criteria, return a tuple from the key, for example key=lambda p: (p.last, p.first). Tuples compare item by item, so the second field only breaks ties in the first.

map() and filter()

map(func, items) applies a function to every item, and filter(func, items) keeps the items for which the function returns a truthy value. Both return lazy iterators, so wrap them in list() to see the results. In modern Python, list comprehensions (next chapter) usually express the same idea more readably.

Common mistakes

  • Trying to put statements, such as an assignment or if block, inside a lambda. Only one expression is allowed; write a def instead.
  • Calling the key yourself: key=str.lower() is wrong. Pass the function, not its result.
  • Forgetting reverse=True exists and negating keys by hand.

Summary

  • lambda args: expression creates a small anonymous function.
  • key= tells sorting and min/max what to compare.
  • Python's sort is stable; return a tuple to sort by several fields.

Quiz: Lambda and sorting keys

1. What does (lambda x, y: x + y)(2, 3) return?

The lambda is called immediately with 2 and 3 and returns their sum.

2. What does sorted(["b", "A", "c"]) return?

Uppercase letters sort before lowercase, and A is the only uppercase one.

3. Which call finds the longest word in words?

Pass the function len itself as the key.

Official docs

Written under the pen name Ethan Cole with AI-assisted drafting. Every code example on this page is executed by our test suite before publishing. Found a mistake? Tell us.