Python Practice › Iterator & Generator Programs › Program 13
Running total
Write a generator that yields the running total of a list.
Output
[5, 8, 16, 18] [5, 8, 16, 18]
Approach
- Keep a total and yield after each addition; compare with
itertools.accumulate.
Solution
from itertools import accumulate def running_total(numbers): total = 0 for n in numbers: total += n yield total print(list(running_total([5, 3, 8, 2])), list(accumulate([5, 3, 8, 2])))Output
[5, 8, 16, 18] [5, 8, 16, 18]
Learn the concept
New to this topic? Read the lesson, then come back.