Decisions & Loops · Lesson 56

Common Loop Patterns

Many loops implement a small number of recurring patterns: accumulate a result, count matches, filter items, search for a first match, transform each item, or process paired/indexed values.

ConceptWorked examplePracticeKnowledge check
Textbook walkthrough

Common Loop Patterns

Many loops implement a small number of recurring patterns: accumulate a result, count matches, filter items, search for a first match, transform each item, or process paired/indexed values. Recognising the pattern helps you choose between an explicit loop and a clearer built-in, comprehension or library operation.

Learning goal: explain why Common Loop Patterns behaves this way, apply it to a small example, and verify the result independently. Begin by being able to justify this first step: State the accumulator or output before the loop.

Deeper walkthrough

Read Common Loop Patterns as a mechanism, not a recipe

Treat this as a sequence of observable decisions rather than one opaque command. Stage 1: State the accumulator or output before the loop. Stage 2: Update it once per relevant item. Stage 3: Keep filtering conditions close to the update they control. Final checkpoint: After the loop, verify the result on a list small enough to trace by hand.

Mechanism

Follow the transformation

State the accumulator or output before the loop.

Update it once per relevant item.

Keep filtering conditions close to the update they control.

Evidence

Know what would convince you

  • Trace a tiny input by hand and compare the runtime result.
  • Inspect type, value/shape and any mutation/side effect explicitly.
Useful distinctionInput: Objects/values supplied to the operation.
Click a stage to inspect what happens, what changes, and what should be checked before moving on.
Stage 1

State the accumulator or output before…

State the accumulator or output before the loop. Treat the output from Common Loop Patterns as evidence to inspect: confirm its type, shape, range or units and connect it back to the input that produced it.

Output focus: inspect both the value and its shape/type/meaning before treating it as a trustworthy result.
How it works

Trace the mechanism step by step

  1. State the accumulator or output before the loop.
  2. Update it once per relevant item.
  3. Keep filtering conditions close to the update they control.
  4. Use enumerate when both position and value are needed; use zip for aligned sequences.
  5. After the loop, verify the result on a list small enough to trace by hand.
Worked demonstration

Accumulator and filter

# Step 1 — Compute the right-hand expression and store its result in `amounts` for the next step.
amounts = [10, 80, 25, 120]
# Step 2 — Compute the right-hand expression and store its result in `total_large` for the next step.
total_large = 0
# Step 3 — Iterate through the collection so the indented block is applied once for each item.
for amount in amounts:
    # Step 4 — Evaluate this condition and execute the indented branch only when the condition is true.
    if amount >= 50:
        # Step 5 — Execute this statement and inspect how it changes the current value, object or program state.
        total_large += amount
# Step 6 — Display the current value explicitly so the result/state can be inspected during execution.
print(total_large)
Expected / illustrative result
Only 80 and 120 satisfy the condition, so the accumulator finishes at 200.
Interpret the result.

For Common Loop Patterns, trace the specific input through the mechanism above and independently verify one returned value, state change or side effect.

Distinctions & related ideas

Place the concept correctly

InputObjects/values supplied to the operation.
StateNames or mutable objects that may change during execution.
OutputReturned value, side effect, file, plot or exception to inspect.
Use deliberately

When it is appropriate

Use Common Loop Patterns when it answers a defined question in Decisions & Loops and its inputs/assumptions match the current data or program state.

Boundary conditions

When to stop or reconsider

Reconsider Common Loop Patterns when the required information is unavailable, the operation would violate a validation/data boundary, or a simpler operation answers the question more transparently.

Common mistakes

Failure modes to recognise

  • Running the operation on the wrong object/type or in the wrong environment.
  • Inferring correctness from “no exception” without checking the produced value/state.
  • Hiding a boundary case instead of making its behaviour explicit.
Verification

How to check the result

  • Trace a tiny input by hand and compare the runtime result.
  • Inspect type, value/shape and any mutation/side effect explicitly.
  • Run an edge or invalid case and confirm the exception/behaviour is deliberate.
Hands-on practice

Demonstrate understanding

Try this:

Construct a tiny example of Common Loop Patterns. First state the accumulator or output before the loop. Then update it once per relevant item. Predict the result before execution and explain one boundary or failure case.

Use the smallest values that expose the language rule. Write the expected value and type first, then compare the actual state/output with that prediction.
Knowledge check

Check reasoning, not memorisation

Which approach best demonstrates understanding of Common Loop Patterns?

Quick reference

Remember the logic

Step 1State the accumulator or output before the loop.
Step 2Update it once per relevant item.
Step 3Keep filtering conditions close to the update they control.
Step 4Use enumerate when both position and value are needed; use zip for aligned sequences.
Lesson summary

What to remember

  • Many loops implement a small number of recurring patterns: accumulate a result, count matches, filter items, search for a first match, transform each item, or process paired/indexed values. Recognising the pattern helps you choose between an explicit loop and a clearer built-in, comprehension or library operation.
  • State the accumulator or output before the loop.
  • Running the operation on the wrong object/type or in the wrong environment.
  • Trace a tiny input by hand and compare the runtime result.