We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Reduce

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

Assignment

Complete the join and the join_first_sentences functions.

      1. A doc_so_far string – the combined sentences so far, similar to sum_so_far in the example above.
      2. A sentence string – the next sentence to add.
    1. 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
      
      1. A list of sentence strings
      2. An integer n

Use 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.