Concepts / Looping Over Arrays with For Loops

Looping Over Arrays with For Loops

Whole-array problems are solved by visiting every element with a for loop and combining what you find.

  • Programming
Interactive lab

Try it: Loop Tracer

How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.

How it works

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. After the last item the loop ends and the accumulator holds the answer.

Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.

Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.

Educational simulation

Loading the simulation…

Questions That Need the Whole Array

Once you can store many values in one array, the next question is usually about the array as a whole. What is the typical value of the numbers stored there? Which one is the biggest? Neither question can be answered by looking at a single element. Each one requires visiting every position in the array and combining what you find along the way.

This article works through two classic whole-array problems. The first asks for the average of all the elements. The second asks for the largest element. Both are solved with a for loop, and both show a pattern you will reuse many times: keep a small amount of running information, update it as you move through the array, and read the answer once the loop finishes.

What do you think happens?

Before reading on: if you need the largest value in an array, what single piece of information do you think the loop must remember as it goes?

Reveal answer
Answer:

The largest value seen so far, stored in a variable the course calls max.

The loop does not need to remember anything else. Each time it meets a larger element, the remembered value is replaced.

Visiting Every Position with a For Loop

A for loop used on an array visits the positions one at a time, so every element gets examined exactly once. Think of the array as a row of numbered slots. The loop's job is to walk from the first slot to the last, and at each slot it does some work with the value it finds there.

A[0]4A[1]9A[2]2A[3]7next passnext passnext pass
Which index does the loop visit on each pass, and how does that map onto the positions of the array's elements from first to last?

The diagram uses the array [4, 9, 2, 7] as a concrete example. The first pass sees the element at position 0, the next pass sees position 1, and so on until the last position has been examined. The loop never needs to know the values in advance; it only needs to reach every position.

Accumulating a Sum in One Loop

Suppose A is an array of doubles and you want the average of all its elements. The source approach has two stages. First, a for loop adds up every number in the array. Second, the total is divided by the length of the array. The result is the average.

python
Output (expected)
5.5
Notes on the code
  • total starts at zero and is the only value that changes during the loop
  • the loop body only adds the current element to total
  • the division happens once, after the loop has finished

Notice that the loop only does the adding. The division happens once, after the loop has finished. Dividing inside the loop would produce a wrong answer, because you would be dividing partial totals instead of the complete sum. The two stages are separate on purpose.

The total is the only quantity that changes while the loop runs. Data enters as individual array elements, is collected into a single running total, and only becomes an average after the division step. Each pass adds one more element, so the running total grows until it holds the sum of everything in the array.

Tracing the Running Maximum

A second common task is to find the largest number in an array. The strategy is to walk through the array while remembering the largest value seen so far. That remembered value is stored in a variable, which this course will call max. Whenever the loop meets an element larger than the current value of max, max is updated to that larger element. The loop does not need to remember anything else.

max = 4start with A[0]max = 9visit 9, largermax = 9visit 2, not largermax = 9visit 7, not largerpass 1pass 2pass 3
After each iteration, what is the current value of the tracking variable, and when does it change to a new element?
Position iElement A[i]Comparison resultmax after the pass
0 (start)4max set to A[0]4
199 is larger, so update9
222 is not larger, no update9
377 is not larger, no update9

Trace of the running maximum over the array [4, 9, 2, 7]

python
Output (expected)
9
Notes on the code
  • max_val starts with A[0], which is an element of the array
  • the loop begins at index 1 because position 0 is already in max_val
  • max_val changes only when a larger element appears

When the loop finishes, every element has been examined, and max holds the largest item in the whole array. The important feature of this method is that the answer is not known in advance. It is built up one comparison at a time, and only the final state of max reveals the result.

Why the Starting Value Matters

A question remains before the loop can start: what should max contain at the beginning? Whatever you choose must be a value that the array can actually provide, or the comparison logic will not behave correctly. The starting value is not a detail; it determines what the loop can ever report.

One reasonable choice is to start max at the first element, A[0], and then examine the remaining elements starting from A[1]. Because the first element is already in max, the loop only needs to compare against the rest of the array. This choice guarantees that max begins with a value that really is in the array.

max = -5start at A[0]max = 0start at 0max = -2after visiting -2max = 0no element is largerresult: -2correct largestresult: 00 is not in the arrayvisit -2finishvisit -2finish
If the tracker starts at 0 versus at the first element, how does the result differ when every array value is negative?

What do you think happens?

The array is [-5, -2, -8]. If max starts at 0 and the loop only replaces max when it finds a larger element, what does the loop report?

Reveal answer
Answer:

0

No element of the array is larger than 0, so max is never updated. The reported value is not an element of the array at all, which is exactly why starting at A[0] is the safer choice.

Mistakes Beginners Make

  • Common mistake

    Dividing by the length inside the loop

    What it looks like
    for each element: total += A[i]; average = total / len(A)
    Why it fails

    Each division uses a partial total instead of the complete sum, so the value stored in average changes on every pass and does not match the true average.

    Do this instead

    Add inside the loop, then divide once after the loop has finished.

  • Common mistake

    Starting max at 0 when values may be negative

    What it looks like
    max = 0 for the array [-5, -2, -8]
    Why it fails

    No element is larger than 0, so max is never updated and the result is 0, a value that is not in the array.

    Do this instead

    Start max at A[0] so the starting value is always an element of the array.

  • Common mistake

    Forgetting to update max only when a strictly larger element appears, which makes the tracker lose the meaning of 'largest seen so far'

Practice: Trace the Maximum

EASY

Trace the running maximum for the array [3, 8, 8, 1, 6]. Start max at A[0], then write the value of max after each pass of the loop from index 1 to the end. Which pass, if any, changes max, and what is the final result?

Hints
  • Start by writing max = 3 for position 0.
  • Only update max when the current element is strictly larger than max.
  • The value 8 appears twice; ask whether the second 8 changes max.

Key Takeaways

  • A for loop can visit every element of an array, and combining what it finds yields a whole-array answer.
  • To compute an average, add every element inside a single loop, then divide the total by the array length once after the loop finishes.
  • To find the largest element, keep a running maximum in max and update it whenever the loop meets a larger element.
  • Start max at A[0] so the starting value is an element of the array; a starting value such as 0 can give a wrong result when all values are negative.