Functional programming (map, filter, reduce)
Computer Science · Software engineering
Question 1 of 10
0Which of these operations changes the original list in place?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Functional programming (map, filter, reduce) explained
Functional programming is a style in which programs are built from functions that take inputs and return outputs without changing anything else. A pure function always gives the same result for the same inputs and has no side effects, such as altering a global variable or printing inside the calculation. Data is treated as unchanging, so instead of editing a list, a function creates a new list. This makes programs easier to test and to run in parallel.
Functional languages rely on higher-order functions, which take other functions as arguments. Three common examples are map, which applies a function to every item in a list; filter, which keeps only the items that pass a test; and reduce, which combines all the items into one value using an operation such as addition. Chaining these three operations often replaces a loop with a short, readable expression. Because the original list is never changed, the same input always produces the same output, which makes each step easy to check.
Worked example
Find the sum of the squares of the even numbers from 1 to 6.
- Start with the list 1, 2, 3, 4, 5, 6.
- filter keeps the even numbers: 2, 4, 6.
- map squares each number: 4, 16, 36.
- reduce adds them, starting from 0: 0 + 4 + 16 + 36 = 56.
The result is 56. Each step creates a new list and changes nothing else, so each step can be tested on its own.
What you will practise
70 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- What is a higher-order function?
- What does map do to a sequence?
- What does filter do to a sequence?
- What does reduce do to a sequence?
- What is a pure function?
- What is a lambda (anonymous) function?
- What does immutable data mean in functional programming?
- What is the output of list(map(lambda x: x * 2, [1, 2, 3]))?
…and 62 more.