Skip to main content
Albero Academy

Lambda Functions

Small anonymous functions for short, throwaway logic.

Functions8 min

A lambda is a small anonymous function written in a single expression. It's most useful when you need a throwaway function to pass as an argument — a sort key, a map, a filter — without the ceremony of a full def.

The syntax

lambda args: expression. The expression's value is returned automatically — no return keyword, and only one expression allowed:

lambda vs def
square = lambda x: x * x
square(5) # 25
# Exactly equivalent to:
def square(x):
return x * x

The real use: sort keys

The everyday use of a lambda is the key= argument to sorted/min/max:

sorting by a computed key
students = [{"name": "Ana", "pkg": 7.5}, {"name": "Ravi", "pkg": 9.0}]
students.sort(key=lambda s: s["pkg"], reverse=True) # by package, high→low
sorted(words, key=lambda w: len(w)) # by length
max(students, key=lambda s: s["pkg"]) # the top earner

With map & filter

lambdas with map/filter
nums = [1, 2, 3, 4]
list(map(lambda n: n * n, nums)) # [1, 4, 9, 16]
list(filter(lambda n: n % 2 == 0, nums)) # [2, 4]
# (though a comprehension is often clearer: [n*n for n in nums])

Key takeaways

  1. 01lambda args: expression is a small anonymous single-expression function.
  2. 02Its value is returned automatically — no return keyword.
  3. 03Its main use is the key= argument to sorted/min/max.
  4. 04It also pairs with map/filter (though comprehensions are often clearer).
  5. 05For anything non-trivial, prefer a named def.

Finished this chapter?

Mark it complete to track your progress through Python.