accumulation pattern

A loop pattern that builds a result step by step, starting from an initial value and combining each item into it, such as adding up a list.

In more detail

The initial value must match the operation: 0 for a sum, 1 for a product, "" for joining strings, [] for building a list. Each pass does result = result + item, or the matching operation, and the answer is ready after the loop.

Example

total = 0
for n in nums:
    total = total + n

Related terms

Taught in

References