Part I — Foundations · Chapter 3 · Lesson 3 of 5 · 9 min read
Lesson 3: for Loops, Ranges, and Collection Iteration
Lesson level: Foundation
Purpose: Iterate clearly over ranges and collections when the sequence of values is already defined.
Learning objectives
By the end of this lesson, you should be able to:
- write a for loop over an iterable value;
- explain how the iteration variable is bound;
- use range-produced numeric sequences;
- iterate through lists, strings, and string-keyed maps appropriately;
- trace collection iteration in source order;
- apply counting, filtering, transformation, and aggregation patterns;
- compare for loops with while loops; and
- avoid mutation and scope defects during iteration.
3.1 When a for loop fits
Use a for loop when the program should process each value produced by an iterable. The loop controls traversal, so the body can focus on the work for one value.
Typical cases include visiting every item in a list, every character in a string, every key in a map, or every number in a generated range.
3.2 Basic syntax
let colors = ["red", "green", "blue"]
for color in colors {
print "Color: {color}"
}
The iterable expression is evaluated, then each produced value is assigned to the iteration variable color before the body executes. When no values remain, execution continues after the loop.
3.3 Iteration order
List and string iteration follow their sequence order. Map iteration follows the runtime’s key iteration behavior; write logic that treats keys as data rather than depending on an undocumented order.
For the color example, the output order is red, green, then blue because that is the list’s source order.
3.4 The iteration variable
The name after for is bound for the current iteration. Choose a singular name that describes one element: case for a list of cases, character for a string, or key for map keys.
Do not use the same name for the collection and its element. for item in items communicates their relationship; for items in items obscures it.
3.5 Loop scope
The loop body executes in a nested environment. The iteration variable and body-local declarations are available inside the iteration but not after the loop. Assignments can still update mutable bindings in an enclosing scope, which enables accumulators.
3.6 Numeric ranges
Use a range-producing value when the loop should visit a predictable numeric sequence. PeaLang’s range support produces integers from a start toward a stopping boundary with an optional step.
for number in range(1, 6) {
print number
}
This visits 1, 2, 3, 4, and 5. The stopping boundary is excluded. Think of the sequence as beginning at start and continuing while another step remains on the permitted side of stop.
3.7 Start, stop, and step
| Expression | Produced values |
|---|---|
| range(0, 5) | 0, 1, 2, 3, 4 |
| range(1, 6) | 1, 2, 3, 4, 5 |
| range(2, 11, 2) | 2, 4, 6, 8, 10 |
| range(5, 0, -1) | 5, 4, 3, 2, 1 |
The sign of step must move from start toward stop. A positive step with a descending boundary, or a negative step with an ascending boundary, produces no values. A zero step is invalid.
3.8 Range boundary reasoning
To include a desired final integer, choose a stop beyond it in the step direction. To process 1 through 10 with step 1, use stop 11. To process 10 down through 1 with step -1, use stop 0.
Before running a range loop, write the first expected value, final expected value, and value that would cross the stop boundary.
3.9 Trace a range loop
let total = 0
for number in range(1, 4) {
total += number
}
print "Total: {total}"
| Iteration | number | total after body |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
The final output is Total: 6. Unlike a while loop, the range controls the next numeric value; the body does not manually update number.
3.10 Iterating through lists
let scores = [72, 88, 91, 65]
let total = 0
for score in scores {
total += score
}
print "Total score: {total}"
Each score is read in list order. The enclosing total binding is updated once per element. The original list is not changed.
3.11 Iterating through strings
A string can be traversed one character at a time:
let text = "pea"
for character in text {
print character
}
The output contains p, e, and a in order. Use string-library functions when the task is better expressed as a whole-string operation; use iteration when each character requires separate logic.
3.12 Iterating through maps
Map iteration exposes keys. Use the key to retrieve the corresponding value.
let limits = {"time": 30, "memory": 256}
for key in limits {
print "{key}: {limits[key]}"
}
Do not build policy meaning around a particular key order unless the interface explicitly guarantees it. If order matters, represent the desired order as a list.
3.13 Counting pattern
let scores = [72, 88, 91, 65]
let passing_count = 0
for score in scores {
if score >= 70 {
passing_count += 1
}
}
The final count is 3. The count changes only when the current element satisfies the condition.
3.14 Filtering pattern
Filtering retains elements that satisfy a condition. Before using higher-level collection helpers, the pattern can be expressed explicitly:
let scores = [72, 88, 91, 65]
let passing = []
for score in scores {
if score >= 70 {
passing = passing + [score]
}
}
The result preserves the relative order of accepted elements. Later collection lessons introduce reusable transformation and filtering operations.
3.15 Transformation pattern
A transformation produces one output value for each input value.
let values = [1, 2, 3]
let doubled = []
for value in values {
doubled = doubled + [value * 2]
}
The result is [2, 4, 6]. Keep the original and transformed collections distinct when in-place mutation would make iteration harder to reason about.
3.16 Aggregation pattern
An aggregation combines many elements into one result, such as a total, count, minimum, maximum, or summary map.
let values = [4, 7, 2]
let maximum = null
for value in values {
if maximum == null or value > maximum {
maximum = value
}
}
The null initial state represents “no value processed yet.” After a nonempty list is processed, maximum contains the greatest observed value. For an empty list, it remains null.
3.17 Index-aware iteration
When both position and value are needed, use a numeric range and index the collection carefully.
let names = ["Ana", "Ben", "Chen"]
for index in range(0, 3) {
print "{index}: {names[index]}"
}
The upper boundary must match the collection length. Hard-coded lengths are acceptable for a small fixed example but fragile for changing data. Prefer a collection-length operation when introduced by the relevant library lesson.
3.18 for versus while
| Question | Prefer for | Prefer while |
|---|---|---|
| What controls repetition? | An iterable supplies values | A changing condition |
| Is manual progress needed? | Usually no | Usually yes |
| Typical use | Visit each item or range value | Retry, converge, or continue until state changes |
| Main risk | Wrong iterable or boundary | Nontermination or stalled progress |
If the program already has a sequence of values, a for loop usually communicates intent better. If repetition depends on a condition that changes unpredictably, a bounded while loop is often appropriate.
3.19 Mutation during iteration
Avoid structurally changing the collection being traversed unless the behavior is explicitly defined and tested. Adding or removing elements can skip values, repeat values, or produce engine-dependent results.
Prefer building a separate result collection. If the task requires controlled in-place updates, use indices with validated bounds and document the mutation contract.
3.20 Common mistakes
- Expecting the stop value to be included: range stopping boundaries are excluded.
- Using the wrong step direction: the range may produce no values.
- Using a zero step: a range cannot advance.
- Manually updating the iteration variable: the iterable supplies the next value.
- Using a hard-coded length for changing data: indexing can become invalid.
- Depending on map key order: represent required order explicitly.
- Reusing the collection name as the element name: choose distinct singular and plural names.
- Expecting body-local names after the loop: loop scope ends with the iteration.
- Mutating the traversed collection: build a separate result unless the contract is explicit.
- Ignoring the empty iterable: the body may execute zero times.
3.21 Guided practice
- Write a range that produces 1 through 5.
- Write a range that produces even numbers from 2 through 10.
- Write a descending range that produces 5 through 1.
- Predict the output of range(3, 3).
- Trace a sum over [4, 6, 8].
- Count values greater than 10 in a sample list.
- Explain why a map loop should not assume a key order.
- Choose for or while for a fixed list, a retry process, and numerical convergence.
- Rewrite a loop that mutates its input list so it builds a separate result.
- Explain what happens when the iterable is empty.
3.22 Iteration-design checklist
- Identify the iterable or stopping condition.
- Write the expected first and final values.
- Confirm range stop exclusion and step direction.
- Name the element and collection distinctly.
- Decide which enclosing results the body may update.
- Handle an empty iterable deliberately.
- Avoid changing collection structure during traversal.
- Trace representative, boundary, and empty cases.
3.23 Hands-on lab: Build a score analyzer
Create score_analyzer.pea using a source-defined list of numeric scores.
Requirements:
- Print each score with its position.
- Calculate total and count.
- Count scores at or above a passing threshold.
- Build a separate list of passing scores.
- Track minimum and maximum with a safe empty-list design.
- Print a labeled summary with a stable reason or status code.
- Do not structurally modify the input list while traversing it.
- Test a normal list, a one-element list, and an empty list.
For the foundation version, use a fixed list length for index-aware output and document that limitation. Also implement a value-only loop that remains correct when the list contents change.
Deliverable: The source file, expected and actual output for all three cases, iteration traces, a boundary explanation for the passing threshold, and a note comparing value-only with index-aware traversal.
3.24 Review questions
- What does a for loop receive from its iterable?
- When is the iteration variable bound?
- How do list and string iteration orders behave?
- Why should map logic avoid assuming an undocumented key order?
- Why is the stop value excluded from a numeric range?
- How must the step direction relate to start and stop?
- What does a zero-length range do?
- How does an accumulator update an enclosing binding?
- How do counting, filtering, transformation, and aggregation differ?
- When is index-aware iteration justified?
- Why is a separate result collection safer than modifying the traversed collection?
- When should a for loop be preferred over a while loop?
3.25 Applied challenge
Extend the score analyzer into a small rules report. Iterate over a fixed list of case-impact scores, classify each score by the Chapter 3 threshold policy, build separate lists for low, medium, and high results, count each class, and calculate a total. Preserve source order, handle an empty list, and compare a value-only traversal with an index-aware version.
Lesson summary
A for loop processes values supplied by an iterable and is usually the clearest choice for ranges and collections. Range boundaries are stop-exclusive, step direction controls whether values are produced, and collection traversal must respect scope and ordering contracts. Counting, filtering, transformation, and aggregation use enclosing accumulators or separate result collections. Careful boundary reasoning, empty-input handling, and avoidance of structural mutation make iteration predictable.
Lesson status: Approved.