Legends ofPythos
Claim your name
Pythonic Python

lambda, map and filter

Lesson 5 of 12

Watch the lesson5:44 ยท with Sigrid

Lambda Functions

You already know how to define functions with def. Python also lets you write a tiny function in one line, with the word lambda. You met it when sorting. It's handy for a quick job, especially when you hand a function to another function, such as sorted(), map() or filter().

A lambda is still an ordinary function. You can write it right where you need it and use it once, or store it in a name and call it as often as you like, just as you would a def 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. Each one takes a function, then an iterable (anything a for loop can go through, such as a list), and uses the function on every item:
  • map(func, items) runs each item through your function, and hands out the results.
  • filter(test, items) runs your test on each item, and keeps only the items where it gives 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
nums = [3, 8, 15, 22, 9]
evens = list(filter(lambda n: n % 2 == 0, nums))
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 how many letters they have. The lambda lambda w: len(w) tells Python to compare each word by its length, not by its letters. For length alone, key=len does the same job. A lambda earns its place when the key needs working out: key=lambda w: w[-1] sorts by each word's last letter.

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. (key=len would sort the same way, but here the point is to practise writing a lambda.)
players = ['Jules', 'Max', 'Priya']

Run your code to check it against the tests.