Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.9 — Functional Style in Python
Python · Example 1 of 2

Pure functions, map, filter, reduce

Try replacing the lambda in filter with a named function. Note that scores.sort() returns None.

Functional style means building programs from small pure functions that take values and return new values, instead of changing things in place. Python mixes it freely with other styles: map, filter, reduce, comprehensions, operator and immutable data are its tools.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a pure function double_all(numbers) that returns a new list with every number doubled, without changing the input. Show that the input is unchanged.

02

Sort [("pen", 10), ("bag", 120), ("book", 250)] by the price (second item) from highest to lowest using operator.itemgetter.

03

Use reduce and operator.mul to compute the product of [2, 3, 4], then do the same with math.prod (a built-in helper that multiplies all the numbers in a list) and compare.

Explain it without notes

01

What is a pure function and what are its benefits?

02

When would you choose a comprehension over map and filter, and when the reverse?

03

Why does list.sort() return None, and what is the functional alternative?

04

What do operator.itemgetter and operator.attrgetter do?

Pure functions, map, filter, reduce
Sign in to run this example in your browser.

Expected output

map:           [11.8, 29.5, 47.2, 5.9]
comprehension: [11.8, 29.5, 47.2, 5.9]
filter:        [10, 25, 40]
comprehension: [10, 25, 40]
reduce:        80
sum:           80
(1, 2, 3) (1, 2, 3, 4)
sorted copy: [1, 2, 3] original: [3, 1, 2]
sort in place returns: None now: [1, 2, 3]