Lambda, map() & filter()

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What is a Lambda?

Sometimes you need a tiny function — just one line — and giving it a name feels like overkill. Python lets you create anonymous functions (functions without a name) using the `lambda` keyword.

The syntax is: `lambda parameters: expression`

# Regular function def double(x): return x * 2 # Same thing as a lambda double_lambda = lambda x: x * 2 print(double(5)) print(double_lambda(5))

Both do the exact same thing. But the lambda is just one line — no `def`, no `return`, no name needed.

Exercise 2 — Lambda Syntax

A lambda can take any number of parameters, but it can only have one expression (no `if` blocks, no loops, no multiple lines).

add = lambda a, b: a + b greet = lambda name: f"Hello {name}!" no_args = lambda: "No arguments!" print(add(3, 7)) print(greet("Aquachu")) print(no_args())

When to use lambda?

Lambda is best for short, simple operations. If your function needs multiple lines or is complex, use a regular `def` function instead.

Exercise 3 — Lambda Output

What is printed?

power = lambda level: level * 10 print(power(5))
Options
• 5
• 50
• 10
• Error

Hint : The lambda multiplies the input by 10.

Exercise 4 — Write a Lambda

Complete the lambda that calculates a Codémon's attack power (level times 3).

Hint : Start with the `lambda` keyword. The attack formula multiplies level by 3.

Exercise 5 — Lambda with sorted()

The most common use of lambda is with `sorted()`. You can pass a lambda as the `key` parameter to sort by any criteria.

team = [("Aquachu", 15), ("Pyrochu", 25), ("Florachu", 10)] by_level = sorted(team, key=lambda x: x[1]) print(by_level)

`key=lambda x: x[1]` tells `sorted()` to use the second element (the level) for comparison. Without it, Python would sort by the first element (the name).

To sort in reverse order (biggest first), just add `reverse=True`:

team = [("Aquachu", 15), ("Pyrochu", 25), ("Florachu", 10)] by_level_desc = sorted(team, key=lambda x: x[1], reverse=True) print(by_level_desc)

Exercise 6 — Sorted with Lambda

What is printed?

team = [("Zap", 30), ("Aquachu", 10), ("Pyrochu", 20)] result = sorted(team, key=lambda x: x[1]) print(result[0][0])
Options
• Zap
• Aquachu
• Pyrochu
• 30

Hint : The list is sorted by level (index 1) in ascending order. The lowest level is 10.

Exercise 7 — Sort by Name Length

Complete the code to sort Codémon by the length of their name.

Hint : You need a `lambda` that returns the length of each name using `len()`.

Exercise 8 — map() — Transform Every Element

`map()` applies a function to every element in a list. It's like a list comprehension but uses a function instead.

levels = [5, 10, 15, 20] doubled = list(map(lambda lv: lv * 2, levels)) print(doubled) # Same as: doubled2 = [lv * 2 for lv in levels] print(doubled2)

`map(function, list)` returns a map object — wrap it in `list()` to see the results. Both approaches give the same result!

Exercise 9 — Using map()

Complete the code to double all levels using `map()` and a lambda.

Hint : The lambda parameter name must match the variable used in the expression.

Exercise 10 — filter() — Keep Only Matching Elements

`filter()` keeps only the elements where the function returns `True`. It's like a list comprehension with an `if`.

levels = [5, 12, 3, 25, 8, 30] strong = list(filter(lambda lv: lv >= 10, levels)) print(strong) # Same as: strong2 = [lv for lv in levels if lv >= 10] print(strong2)

Exercise 11 — filter() Result

What is printed?

names = ["Aquachu", "Zap", "Florachu", "Pyrochu"] short = list(filter(lambda n: len(n) <= 5, names)) print(short)
Options
• ["Aquachu", "Florachu", "Pyrochu"]
• ["Zap"]
• ["Aquachu", "Zap"]
• []

Hint : `filter()` keeps names where `len(n) <= 5`.

Exercise 12 — Lambda, map, filter

Match each expression with its description.

Items to match
• `lambda x: x * 2`
• `map(func, list)`
• `filter(func, list)`
• `sorted(list, key=func)`
• `lambda: "hi"`
Definitions
• Anonymous function that doubles
• Apply function to every element
• Keep elements where function returns True
• Sort using a custom criteria
• Lambda with no parameters

Exercise 13 — Codémon Team Manager

Use lambda, map, and filter to manage your team! Given a list of tuples `(name, element, level)`: 1. Use `filter()` to keep only Codémon with level >= 15 2. Use `map()` to create formatted strings like `"Aquachu (Water) - Lv.15"` 3. Use `sorted()` with a lambda to sort the original team by level (highest first) 4. Print each result

Starter code
team = [("Aquachu", "Water", 15), ("Pyrochu", "Fire", 25), ("Florachu", "Plant", 8), ("Zap", "Electric", 30), ("Rockachu", "Rock", 12)] # 1. Filter: level >= 15 # 2. Map: format as strings # 3. Sort by level (highest first) # Print results
Back to the course