Concepts / Using for Loops

Using for Loops

A for loop repeats a block of code for each item in a sequence, assigning each item to a loop variable one at a time.

  • 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…

One Item at a Time

Suppose a task must be performed for every item in a sequence. A for loop handles this repetition by taking one item from the sequence, assigning it to a loop variable, and repeating the loop body. After that iteration, it takes the next item and does the same thing. The central question is not how many times to repeat blindly, but which item is being processed during the current iteration.

Sequenceitem A, item B, item Citem Aloop variableone current itemLoop bodyprocess current itemitem Bitem Cfirst itemnext itemnext itemassignassignassignprocess
How does each item move from the sequence into the loop variable and then through the loop body?

Tracing Each Iteration

What do you think happens?

A loop processes the sequence ["red", "green", "blue"] in order. What values does the loop variable receive?

  • Only red

  • red, then green, then blue

  • blue, then green, then red

Reveal answer
Answer:

red, then green, then blue

A for loop assigns each item in the sequence to the loop variable one at a time. The loop body therefore runs once with red, once with green, and once with blue.

Sequencered, green, blueIteration 1current item: redredoutput after iteration 1Iteration 2current item: greengreenoutput after iteration 2Iteration 3current item: blueblueoutput after iteration 3take first itemprocesstake next itemprocesstake next itemprocess
What happens on each iteration, and what output is produced after the loop variable takes each value?

To trace a for loop, write down the sequence in its order. Then move through the sequence one item at a time. For each item, record the value assigned to the loop variable and determine what the loop body does with that value. The complete output is the ordered combination of the results from those iterations.

The range Function

Definition

The range() function generates a sequence of numbers. Its start, stop, and step parameters let you control where the numeric sequence begins, where it ends, and how the values change between items.

FormMeaningGenerated values
range(stop)Begins at the default starting point and advances by the default step of 1 until stop is reachedDepends on stop
range(start, stop)Begins at start and advances by 1, stopping before stopstart through the value before stop
range(start, stop, step)Begins at start and changes by step, stopping before the stop boundaryValues determined by start, stop, and step

The source describes range() as having customizable start, stop, and step parameters. With start and stop, the stop value is not included; the default increment is 1.

range(2, 10, 2)start, stop, step246810stop value excludedfirst value+2+2+2next value would be stop
Which numbers does range(start, stop, step) generate, and where does the sequence stop?

Worked Traces

Worked example

Counting by Two

Predict the values processed by a for loop that uses range(2, 10, 2).

  1. 1
    Read the parameters

    The starting value is 2, the stopping boundary is 10, and the step is 2.

  2. 2
    Begin at start

    The first value is 2.

  3. 3
    Apply the step

    Add 2 repeatedly to obtain 4, 6, and 8.

  4. 4
    Check the boundary

    The stop value 10 is not included, so the sequence ends before 10.

Result

The loop processes 2, then 4, then 6, then 8.

Code walkthrough
for number in range(2, 10, 2):
    print(number)
  1. 1
    range(2, 10, 2) generates 2, 4, 6, and 8.
  2. 2
    The first iteration assigns 2 to number, so the output is 2.
  3. 3
    The next iterations assign 4, 6, and 8 to number in order.
  4. 4
    The value 10 is the stop boundary and is not processed.
  • number receives one value from the numeric sequence on each iteration
  • the loop body processes the current value by printing it
Output
2
4
6
8
Output
2
4
6
8
Worked example

Counting Backward

Determine the values generated by range(5, 0, -1).

  1. 1
    Read the parameters

    The sequence starts at 5, has a stopping boundary of 0, and changes by -1.

  2. 2
    Move backward

    Subtract 1 after each value: 5, 4, 3, 2, then 1.

  3. 3
    Apply the stop rule

    The stop value 0 is not included.

Result

The generated values are 5, 4, 3, 2, and 1.

Choosing the Structure

A for loop is an appropriate control structure when the task involves processing each item in a known sequence. The sequence may contain items such as names or other values, or it may be generated numerically with range(). The loop makes the item-by-item progression explicit: the loop variable represents the current item, and the loop body describes how that item is processed.

Mistakes Beginners Make

  • Common mistake

    Expecting the stop value to be included

    What it looks like
    Assuming range(2, 6) produces 2, 3, 4, 5, and 6
    Why it fails

    The stop value is not included.

    Do this instead

    Trace the sequence as 2, 3, 4, and 5.

  • Common mistake

    Forgetting that the default step is 1

    What it looks like
    Reading range(3, 7) as if it skipped numbers
    Why it fails

    With start and stop specified, the values advance by 1 by default.

    Do this instead

    Use a third parameter when a different increment is required.

  • Common mistake

    Ignoring the direction of the step

    What it looks like
    Expecting range(5, 0, -1) to count upward
    Why it fails

    A negative step makes the values move backward.

    Do this instead

    Use the sign and size of the step to trace the direction and increment.

  • Common mistake

    Treating the loop variable as the whole sequence

    What it looks like

    Thinking the loop variable represents every item at once

    Why it fails

    The loop variable receives one item at a time.

    Do this instead

    Trace the value of the loop variable separately for each iteration.

Practice Trace

MEDIUM

Predict the values processed by this loop before checking your answer: for value in range(10, 4, -2). List the values in the order the loop variable receives them, and identify which stop value is excluded.

Hints
  • Start at 10.
  • Apply a step of -2 after each value.
  • Stop before reaching 4.
Worked example

Practice Answer

Trace range(10, 4, -2).

  1. 1
    Start

    The first value is 10.

  2. 2
    Apply the step

    Subtract 2 to get 8, then 6.

  3. 3
    Check the boundary

    The next value would be 4, but the stop value is excluded.

Result

The loop variable receives 10, then 8, then 6. The excluded stop value is 4.

Key Takeaways

  • A for loop repeats its body for each item in a sequence.
  • The loop variable receives one sequence item at a time.
  • range(start, stop) begins at start, advances by 1 by default, and excludes stop.
  • A third range() parameter controls the step, including backward counting with a negative step.
  • To predict output, list the sequence and trace the loop variable through each iteration.

Related concepts

More concepts starting with U