I want to get a running total from a list of numbers.
For demo purposes, I start with a sequential list of numbers using range
a = range
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can use and increment a variable within a list comprehension:
# items = range(7)
total = 0
[(x, total := total + x) for x in items]
# [(0, 0), (1, 1), (2, 3), (3, 6), (4, 10), (5, 15), (6, 21)]
This:
total
to 0
which symbolizes the running sumtotal
by the current looped item (total := total + x
) via an assignment expressiontotal
as part of the produced mapped tuple