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 + nRelated terms
- successive modification pattern — A loop pattern where a variable is updated a little on every pass, each new value built from the previous one, such as number = number + 1.
- initialisation — Giving a variable its first value before it is used, especially before a loop that updates it.
- for loop — A loop that runs its body once for each item in a list or other collection, setting a loop variable to the current item.
Taught in
- Accumulation Loops — Hands-on Python: Complete Video Course & Book
- Chapter One In One Sitting — Hands-on Python: Complete Video Course & Book
- Appending To Lists, Sets, Constructors — Hands-on Python: Complete Video Course & Book