HomeCourseModule 05 › lambda, map, filter — the functional shortcuts

lambda, map, filter — the functional shortcuts

Module 05 · Functions7 min readIntermediate

What you'll learn

  • Recognise a lambda
  • Use sorted() with a key function
  • Read map() and filter() expressions

What's a lambda?

A one-line function that doesn't get a name. Useful when you need to pass a tiny function to another function.

# With def
def double(x):
    return x * 2

# Same thing as a lambda
double = lambda x: x * 2

You'll mostly see lambdas inline, not stored in variables. The most common use: key= in sorted().

sorted() with a key

people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob",   "age": 25},
    {"name": "Carol", "age": 35},
]

by_age = sorted(people, key=lambda p: p["age"])
# [{'name':'Bob',...}, {'name':'Alice',...}, {'name':'Carol',...}]

by_name_desc = sorted(people, key=lambda p: p["name"], reverse=True)

map() — "apply this function to every item"

names = ["alice", "bob", "carol"]
upper = list(map(str.upper, names))   # ['ALICE', 'BOB', 'CAROL']

# Often clearer as a comprehension:
upper = [n.upper() for n in names]

filter() — "keep items where this is true"

ages = [12, 15, 18, 21, 17, 30]
adults = list(filter(lambda x: x >= 18, ages))   # [18, 21, 30]

# Also clearer as a comprehension:
adults = [x for x in ages if x >= 18]
📝 In practice
Python programmers reach for list comprehensions far more often than map() / filter(). But you'll see all three in the wild — recognise them and you can read any Python code.

Key takeaways

  • lambda x: expression — a tiny anonymous function.
  • Most common use: sorted(items, key=lambda i: i["something"]).
  • map/filter exist; comprehensions are usually clearer.

Sort by multiple keys

Sort the people list above by age ascending, but use name as a tiebreaker. Hint: a lambda can return a tuple.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.