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

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.

first itemnext itemnext itemassignassignassignprocessSequenceitem A, item B, item Citem Aloop variableone current itemLoop bodyprocess current itemitem Bitem C
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.

take first itemprocesstake next itemprocesstake next itemprocessSequencered, green, blueIteration 1current item: redredoutput after iteration 1Iteration 2current item: greengreenoutput after iteration 2Iteration 3current item: blueblueoutput after iteration 3
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

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.

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

Worked Traces

Counting by Two

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

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

Begin at start: The first value is 2.

Apply the step: Add 2 repeatedly to obtain 4, 6, and 8.

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

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

for number in range(2, 10, 2): print(number)

Output
2
4
6
8

Counting Backward

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

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

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

Apply the stop rule: The stop value 0 is not included.

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

  • Expecting the stop value to be included

    The stop value is not included.

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

  • Forgetting that the default step is 1

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

    Fix: Use a third parameter when a different increment is required.

  • Ignoring the direction of the step

    A negative step makes the values move backward.

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

  • Treating the loop variable as the whole sequence

    The loop variable receives one item at a time.

    Fix: 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.

Practice Answer

Trace range(10, 4, -2).

Start: The first value is 10.

Apply the step: Subtract 2 to get 8, then 6.

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

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.