PeaBox Lab › PeaLang › Learn › Chapter 3 › Lesson 3

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:

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

ExpressionProduced 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}"
Iterationnumbertotal after body
111
223
336

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

QuestionPrefer forPrefer while
What controls repetition?An iterable supplies valuesA changing condition
Is manual progress needed?Usually noUsually yes
Typical useVisit each item or range valueRetry, converge, or continue until state changes
Main riskWrong iterable or boundaryNontermination 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

3.21 Guided practice

3.22 Iteration-design checklist

3.23 Hands-on lab: Build a score analyzer

Create score_analyzer.pea using a source-defined list of numeric scores.

Requirements:

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

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.

← Previous Next →