Reduce Function in Python

Level 4110 keystrokes

This multiplies all numbers together using reduce, printing 120. reduce() cumulatively applies a function to sequence elements.

Python code

# Import reduce from the functools module
1from functools import reduce
2
# Create a list of numbers
3nums = [1, 2, 3, 4, 5]
# reduce applies the lambda cumulatively from left to right
# ((((1 * 2) * 3) * 4) * 5): 2 → 6 → 24 → 120
4product = reduce(lambda a, b: a * b, nums)
# Print the final product
5print(product)

Output

120
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 6
  • (× 2
  • )× 2
  • =× 2
  • :× 1
  • [× 1
  • ]× 1
  • *× 1

More Python examples at level 4

← Python typing practice