Concepts / Working with Lists: Creating and Accessing Collections

Working with Lists: Creating and Accessing Collections

A for loop is a definite loop that processes each item in a known collection exactly once.

  • Programming

A Collection in Motion

Suppose a collection contains the items red, green, and blue. A for loop can process those items in order, one item at a time. Because the collection is already known, the loop is a definite loop: it processes each item in the collection exactly once.

colorsred, green, blueredfirst itemgreensecond itembluethird itemfirstnextnext
What happens to each collection item as a for loop progresses?

The For Statement

A for loop has two especially important parts: the iteration variable and the collection. The iteration variable holds the current item. As the loop moves through the collection, that variable changes automatically so that the loop body can work with the current item.

python

In this example, color is the iteration variable and colors is the known collection. The keywords for and in are required. The for statement ends with a colon, and the statement inside the loop is indented.

colorsred, green, bluecolorredprintredcolorgreenprintgreencolorblueprintbluecurrent itemused bynext itemused bynext itemused by
How does the iteration variable change as the loop visits the collection?

Tracing Each Iteration

Worked example

Predicting the Printed Items

Trace the loop and determine what it prints.

animals = ["cat", "dog", "bird"]
for animal in animals:
    print(animal)
  1. 1
    Iteration 1

    The iteration variable animal receives cat. The loop body prints cat.

  2. 2
    Iteration 2

    The iteration variable changes to dog. The loop body prints dog.

  3. 3
    Iteration 3

    The iteration variable changes to bird. The loop body prints bird.

Result

The output appears in collection order: cat, dog, bird. Each item is processed once.

Output
cat
dog
bird
animalscat, dog, birdcatanimal = cat; output catdoganimal = dog; output dogbirdanimal = bird; output birdfirst itemnext itemnext item
What is the current item, iteration-variable value, and output after each iteration?

What do you think happens?

What will this loop print, and in what order?

steps = ["start", "middle", "finish"]
for step in steps:
    print(step)
Reveal answer
Answer:

It prints start, then middle, then finish.

The iteration variable step receives the current item in collection order. The loop processes each known item exactly once.

Positions and Items

A collection can be considered as a group of items arranged in positions. A for loop is useful when the goal is to process every item without manually selecting each position. The loop receives the current item through its iteration variable and advances automatically to the next item.

Position 0redPosition 1greenPosition 2blue
How can the items in a list-shaped collection be viewed by position?

Choosing Loop Types

Questionfor loopwhile loop
When is it a good fit?When the collection and its size are knownWhen the number of iterations is unknown
What controls progress?The loop moves through the known collectionA condition determines whether iteration continues
How does the source describe it?A definite loopBetter for unknown iteration counts

The main distinction is whether the number of iterations is known in advance.

Use a for loop when you know the collection to process and therefore know the set of iterations in advance. A while loop is a better choice when the number of iterations is unknown. The choice is about how the loop's repetition is determined: a known collection for a for loop, or an unknown count for a while loop.

Known collectionfor loopfordefinite loopUnknown countwhile loopwhilecondition-controlledchoosechoose
How does control flow differ when the number of iterations is known or unknown?

Mistakes Beginners Make

  • Common mistake

    Leaving out the required for or in keyword

    What it looks like
    color colors:
        print(color)
    Why it fails

    The loop syntax requires the keywords for and in.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Leaving out the colon after the for statement

    What it looks like
    for color in colors
        print(color)
    Why it fails

    The for statement requires a colon before the indented loop body.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Failing to indent the loop body

    What it looks like
    for color in colors:
    print(color)
    Why it fails

    The statements controlled by the loop must be indented.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Treating the iteration variable as a fixed value

    What it looks like
    for color in colors:
        print("red")
    Why it fails

    The loop's iteration variable is intended to hold the current item and change automatically on each iteration.

    Do this instead
    for color in colors:
        print(color)

Practice the Trace

EASY

Trace this loop before looking at the answer. Write down the iteration variable's value during each iteration and then write the output order.

plans = ["learn", "build", "review"]
for plan in plans:
    print(plan)
Hints
  • List the collection items in their existing order.
  • Assign the first item to plan, then move to the next item.
  • The loop body prints the current value of plan.
Worked example

Practice Solution

Trace the plans loop.

  1. 1
    First iteration

    plan receives learn, so the loop prints learn.

  2. 2
    Second iteration

    plan changes to build, so the loop prints build.

  3. 3
    Third iteration

    plan changes to review, so the loop prints review.

Result

The output order is learn, build, review.

Key Takeaways

  1. 1
    A for loop is a definite loop that processes each item in a known collection exactly once.
  2. 2
    The iteration variable holds the current item and changes automatically on each iteration.
  3. 3
    A for statement requires for, in, a colon, and a properly indented loop body.
  4. 4
    To trace a loop, follow the collection order and record the iteration variable's value at each step.
  5. 5
    Choose a for loop when the collection and iteration count are known; choose a while loop when the number of iterations is unknown.

At a glance

  • A for loop processes each item in a known collection exactly once.
  • The iteration variable receives the current item and changes automatically as the loop progresses.
  • Tracing means following collection order, recording the iteration variable, and predicting the loop body's output.
  • The keywords for and in, the colon, and indentation are all part of the required loop structure.
  • Use for when the iterations are known through a collection; use while when the iteration count is unknown.

Related concepts

More concepts starting with W