Functools Reduce in Python

Level 3110 keystrokes

This uses reduce to compute the product of all numbers in a list.

Python code

# reduce() lives in the functools module
1from functools import reduce
2
# The numbers to multiply
3nums = [1, 2, 3, 4, 5]
# x is the running product, y the next item: (((1*2)*3)*4)*5 = 120
4product = reduce(lambda x, y: x * y, nums)
# Prints 120
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 3

← Python typing practice