Lambdas
Lambda syntax, use with sorted/map/filter, operator module, and when NOT to use lambda
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
A lambda is a small : lambda params: expression
The one thing lambdas cannot do: contain statements (no if/else as statements, no =, no return). They are a single expression.
Primary use case — as a key function:
python people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}] # Sort by age sorted(people, key=lambda p: p['age']) # key= is required! # Sort by name length descending sorted(people, key=lambda p: len(p['name']), reverse=True) # Multi-key sort (tuple) sorted(people, key=lambda p: (p['age'], p['name']))
Common mistake — forgetting `key=`:
python sorted(people, lambda p: p['age']) # TypeError — positional, not keyword sorted(people, key=lambda p: p['age']) # correct
map() and filter() with lambda:
python nums = [1, 2, 3, 4, 5] doubled = list(map(lambda x: x * 2, nums)) # [2, 4, 6, 8, 10] evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4] `` In practice, prefer comprehensions — they are more readable.
When NOT to use lambda:
python # Bad — assigning a lambda to a name defeats the purpose double = lambda x: x * 2 # just write a def # Bad — complex logic in a lambda is unreadable # Good — key= in sorted(), passing as a quick callback
Examples
Multi-key sorting with lambda
Negate a value to reverse sort order without reverse=True for that key
students = [
{'name': 'Alice', 'grade': 90, 'age': 22},
{'name': 'Bob', 'grade': 85, 'age': 23},
{'name': 'Carol', 'grade': 90, 'age': 20},
]
# Sort by grade descending, then by age ascending
result = sorted(students,
key=lambda s: (-s['grade'], s['age']))
# Carol (90, 20), Alice (90, 22), Bob (85, 23)
for s in result:
print(s['name'], s['grade'], s['age'])How well did you understand this?
Next in Python Core
OOP Advanced