Lambda Functions
Small, anonymous, one-expression functions — mainly used inline with sort/filter/map.
A lambda is a small, unnamed function limited to a single expression — whatever that expression evaluates to is automatically returned.
square = lambda x: x * x
print(square(5)) # 25
# equivalent regular function
def square(x):
return x * x
Lambdas can't contain statements (no if/for blocks, no multiple lines, no return keyword) — only a single expression, though that expression can include a ternary.
classify = lambda n: "even" if n % 2 == 0 else "odd"
print(classify(7)) # 'odd'
Where lambdas actually get used
Almost always as a short throwaway function passed into something else — most commonly sorted()'s key argument, or filter()/map().
videos = [
{"title": "Intro", "views": 500},
{"title": "Loops", "views": 2000},
{"title": "Functions", "views": 1200},
]
by_views = sorted(videos, key=lambda v: v["views"], reverse=True)
for v in by_views:
print(v["title"], v["views"])
key=lambda v: v["views"] tells sorted() "use this value to compare items" — without it, sorted() would try to compare dictionaries directly, which fails.
map() and filter()
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda n: n * 2, numbers))
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(doubled, evens)
In modern Python, a list comprehension ([n * 2 for n in numbers]) is usually considered more readable than map/filter + lambda — but you'll see both styles in real codebases, so it's worth recognizing this pattern even if you reach for comprehensions yourself.
- •lambda arguments: expression is a one-expression anonymous function — no statements, no multiple lines, implicit return.
- •Lambdas are almost always used inline, most commonly as sorted()'s key argument.
- •sorted(items, key=lambda x: x['field']) sorts by a specific field instead of comparing whole objects.
- •map(fn, iterable) applies fn to every item; filter(fn, iterable) keeps only items where fn returns truthy.
- •A list comprehension is usually more readable than map/filter + lambda for the same job — both exist in real code, though.
Sorting videos by views with a lambda key
Revision Flashcards
Tap a card to flip it and see the answer.