Traversing a List
Visit each item once, like checking every shelf slot, and use a loop to build a result.
traversal, iteration, loop, list, index, total, accumulatorVisit every shelf slot
Suppose three boxes contain 3, 2, and 4 pencils. To count all the pencils, visit each box and add its count to a running total.
Traversal means visiting the items of a structure. Here it means moving through the list one item at a time. An iteration is one turn of a loop. Neither word means that the items are automatically sorted or changed.
Why traversal is needed and where it is used
We often need information about more than one item: a total price, a count of matching names, or a printed label for each object. Traversal gives the algorithm a chance to inspect each item.
If we must use every value to compute an exact total, skipping an unseen box could miss some pencils. For a search, however, we may stop once we find an answer.
Follow a running total
An accumulator is a variable that remembers a result built over several visits. We start the total at zero because no pencils have been counted yet.
| Visit | Current box | Total after adding |
|---|---|---|
| Before any visit | None | 0 |
| 1 | 3 | 3 |
| 2 | 2 | 5 |
| 3 | 4 | 9 |
After each visit, the total equals the sum of the values already visited. That promise explains why the final total is correct.
Python illustration
def total_values(values):
total = 0
for value in values:
total += value
return total
print(total_values([3, 2, 4]))
print(total_values([]))
for index, value in enumerate([3, 2, 4]):
print(index, value)
Prepared output — not live execution:
9
0
0 3
1 2
2 4
total += value means total = total + value. In for value in values,
value is the item's value, not its index. enumerate supplies both when
the position is useful. An empty list makes no visits, leaving total at zero.
How much work and storage
A complete visit to n items takes O(n) time if the job at each item takes
constant time. The running total uses O(1) extra storage under a fixed-size
numeric model; the algorithm does not build a second list.
If you copy every visited item to a new list, the extra storage becomes O(n). If the loop's body performs another full traversal, the work may become O(n²). The cost comes from what the loop does, not just the fact that it is called a loop. Python's arbitrary-size integers can add further costs for very large totals.
Avoid changing the row while walking through it
Removing items from the same list while iterating can shift later items and cause some to be skipped. For beginner traversal examples, do not change the list's length during the loop. Build a separate result when needed, and account for its storage.
Strings can also be traversed, but their items are text units rather than numbers, so our numeric-total function is not a general text-processing function.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
