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:
square = lambda x: x * xsquare(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:
students = [{"name": "Ana", "pkg": 7.5}, {"name": "Ravi", "pkg": 9.0}]students.sort(key=lambda s: s["pkg"], reverse=True) # by package, high→lowsorted(words, key=lambda w: len(w)) # by lengthmax(students, key=lambda s: s["pkg"]) # the top earner
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
- 01lambda args: expression is a small anonymous single-expression function.
- 02Its value is returned automatically — no return keyword.
- 03Its main use is the key= argument to sorted/min/max.
- 04It also pairs with map/filter (though comprehensions are often clearer).
- 05For anything non-trivial, prefer a named def.
