Legends ofPythos
Claim your name
Pythonic Python

lambda, map and filter

Lesson 5 of 12

Watch the lesson1:06 · with Sigrid

Lambda Functions

Think of a lambda as a disposable tool. You use it once, then throw it away. A regular def function is like buying a hammer: you keep it in your toolbox for future projects. A lambda is like borrowing one from a neighbour just to hang a single picture.

You already know how to define functions with def. Python also lets you write tiny functions inline using the keyword lambda. This saves space when you need a quick function only once, especially as an argument to another function.
# normal function
def sq(n):
    return n * n

# lambda version
sq_lambda = lambda n: n * n

print(sq(5))       # 25
print(sq_lambda(5)) # 25
Comparing def and lambda.
A lambda takes arguments before the colon, and its body is just one expression after it. There are no return statements; Python automatically returns the result of that single line.

Where do you see this in real programs? Imagine processing a list of sensor readings or calculating tax on invoice items. You need to transform each number quickly without writing a whole function definition.

map and filter

map() and filter() are built-in functions that apply a callable to every item in an iterable. They work like assembly lines:
  • map(func, iterable) takes each item, runs it through your function, and outputs the result.
  • filter(pred, iterable) looks at each item and keeps only those where your test returns True.
# map: apply lambda to every number
scores = [70, 85, 92]
doubled = list(map(lambda s: s * 2, scores))
print(doubled) # [140, 170, 184]

# filter: keep only even numbers
numbers = [3, 8, 15, 22, 9]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)   # [8, 22]
map doubles numbers; filter keeps evens.
The example above doubled every score and filtered out odd numbers. Notice that map transforms data while filter selects a subset.

Sorting with a key

The sorted() function accepts an optional key argument. This is where lambdas shine: you tell Python how to compare items by passing a small function that extracts the value used for sorting.

Imagine organising a playlist not alphabetically, but by song duration. You need a key that returns each track's length.
# Sort these words from shortest to longest
words = ["banana", "kiwi", "apple", "fig"]
short_first = sorted(words, key=lambda w: len(w))
print(short_first) # ['fig', 'kiwi', 'apple', 'banana']
Sorting words by length.
This example sorts words by their character count. The lambda lambda w: len(w) tells Python to compare each word based on its length, not its letters.

Your turn

0 of 3 solved

Exercise 1

+35 XP
A smart-home system logged sensor readings in millivolts. Write a lambda called double that takes one reading and returns it multiplied by two (for calibration). Then use map with this lambda to create calibrated from the list raw_readings.
raw_readings = [10, 25, -3]
calibrated = []

Run your code to check it against the tests.

Exercise 2

+35 XP
Create a lambda called is_even that returns True when its argument divides evenly by two. Then use filter() with it to build a list called evens from sample.
sample = [1, 2, 3, 4]

Run your code to check it against the tests.

Exercise 3

+35 XP
You have a list of player names from your five-a-side match in players. Sort them by name length, shortest first, using sorted() with a lambda as the key argument, and store the result in ordered_players.
players = ['Jules', 'Max', 'Priya']

Run your code to check it against the tests.