Full answer
from operator import itemgetter
students = [("Asha", 88), ("Ben", 75), ("Chen", 92)]
print(sorted(students, key=lambda s: s[1], reverse=True))
print(max(students, key=itemgetter(1)))
late = [lambda: i for i in range(3)]
print([f() for f in late])
bound = [lambda i=i: i for i in range(3)]
print([f() for f in bound])Output:
[('Chen', 92), ('Asha', 88), ('Ben', 75)]
('Chen', 92)
[2, 2, 2]
[0, 1, 2]The lambda used as a sort key picks the second item of each tuple, so the students are ordered by marks, and reverse=True puts the highest first. max with the same key finds the top student. operator.itemgetter(1) does the same job and is slightly faster and often clearer.
The late-binding example is a classic trap: every lambda in the first list refers to the same variable i, which is 2 after the loop, so all of them return 2. Binding the current value as a default argument (lambda i=i: i) captures it at creation time.
Assigning a lambda to a name (square = lambda x: x * x) is discouraged by PEP 8; use def square(x): return x * x so tracebacks show 'square' instead of '<lambda>'.
from operator import itemgetter
students = [("Asha", 88), ("Ben", 75), ("Chen", 92)]
print(sorted(students, key=lambda s: s[1], reverse=True))
print(max(students, key=itemgetter(1)))
late = [lambda: i for i in range(3)]
print([f() for f in late])
bound = [lambda i=i: i for i in range(3)]
print([f() for f in bound])Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Lambdas are single-expression functions
- Good as short keys and callbacks
- itemgetter and attrgetter are alternatives
- Closures bind variables late
- Prefer def for named functions
Common mistakes
- Assigning lambdas to names
- Lambdas in loops capturing the loop variable
Follow-ups
- How does functools.partial compare?
- Why do lambdas in a loop all return the same value?
Tips
- Mention late binding