

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Functions As Values
incomplete
2: Anonymous Functions
incomplete
3: First-Class and Higher-Order Functions
incomplete
4: Map
incomplete
5: Filter
incomplete
6: Reduce
incomplete
7: Map, Filter, and Reduce Review
incomplete
8: Zip
incomplete
9: Higher-Order Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
functools.reduce() takes a function and a list of values, combining them from left to right, accumulating a single result as it goes.
# import functools from the standard library
import functools
def add(sum_so_far: int, x: int) -> int:
return sum_so_far + x
numbers: list[int] = [1, 2, 3, 4]
total: int = functools.reduce(add, numbers)
print(total)
# 10
reduce starts by calling add with the first two numbers. Moving left to right, it passes each result and the next number to add:
| Call | Result |
|---|---|
add(1, 2) |
3 |
add(3, 3) |
6 |
add(6, 4) |
10 |
We pass add without () so reduce can call it for us. We're handing over the recipe, not the finished dish.
With just one item, reduce returns that item without calling add:
print(functools.reduce(add, [5]))
# 5
Complete the join and the join_first_sentences functions.
doc_so_far string – the combined sentences so far, similar to sum_so_far in the example above.sentence string – the next sentence to add.doc: str = "This is the first sentence"
sentence: str = "This is the second sentence"
print(join(doc, sentence))
# This is the first sentence. This is the second sentence
nUse list slicing to get the first n sentences.
Here's an example of the expected behavior:
joined: str = join_first_sentences(
[
"This is the first sentence",
"This is the second sentence",
"This is the third sentence",
],
2,
)
print(joined)
# This is the first sentence. This is the second sentence.