Reduce Sum in Python

Level 3106 keystrokes

This uses reduce() to accumulate values by applying a function cumulatively to list items.

Python code

# reduce() lives in the functools module
1from functools import reduce
2
# The numbers to add up
3nums = [1, 2, 3, 4, 5]
# a is the running total, b the next item: (((1+2)+3)+4)+5 = 15
4total = reduce(lambda a, b: a + b, nums)
# Prints 15
5print(total)

Output

15
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