for, which requests successive items from an iterable, and while, which repeats while a condition remains true. Neither spelling guarantees that a calculation finishes: a source can be unbounded, and a condition can remain true indefinitely. Python's language reference specifies these control-flow rules.A pass through two positions
Suppose two fictional positions have market values of 200 USD and 150 USD at the same valuation time. This loop accumulates their total:
position_values = [200, 150] # fictional USD values at one valuation time
total = 0
for value in position_values:
total += value
print(total)
# 350total at its initial value of zero. Iteration describes the process of visiting the items; it does not require storing a new collection of results.The iterable is not the cursor
next(cursor) requests the next item, and exhaustion is signalled by StopIteration. A for loop handles that exhaustion normally. These are the documented iterator rules.The distinction matters when two calculations receive the same input object:
position_values = [200, 150]
cursor = iter(position_values)
print(sum(cursor))
# 350
print(list(cursor))
# []
print(list(position_values))
# [200, 150]sum has consumed the cursor. The empty result on the next line means there are no items left in that iterator; it does not mean the portfolio had no positions. The source list is unchanged. A fresh loop over that list can start again, whereas calling iter(cursor) returns the same cursor and does not rewind it. Every iterator is iterable, so “iterable” alone does not promise repeatable passes. See Python's iterable and iterator definitions.yield to suspend and resume computation as items are requested; it need not compute every result in advance. Once that generator is exhausted, another pass needs a new generator or retained output. Python's generator tutorial explains this suspended state.Before iterating through market events
In stream processing, a diagnostic that drains a one-pass event iterator can leave a later calculation with nothing to process. Combine the needed statistics in one pass, retain an appropriately bounded dataset, or use a source with an explicit replay facility. Turning an unbounded stream into a list is not a workable retention policy.
Also check the source's ordering contract. A Python list is traversed in its sequence order; iteration in general does not promise chronological market events. An event-driven backtester must define how timestamps and event ordering are handled. A loop cannot repair an ambiguous feed merely by visiting every item.
Sources
- Python glossary: iterable and iterator.
- Python built-in types: iterator protocol.
- Python language reference: for and while statements.
- Python tutorial: generators.
Examples checked with Python 3.14.4.