Concepts / Looping with while Loops

Looping with while Loops

A for loop visits each element in a list. During each visit, the loop variable holds the current element's value.

  • Programming

Repeating Work Across a List

Suppose you have a list of friends and want to greet every person with the same message. Writing one print statement for each friend would repeat the same code. A for loop lets you write the greeting once and execute it for every element in the list. The loop performs the same block of work once per element.

Key point

A for loop visits each element in a list. During each visit, the loop variable holds the current element's value.

One Value at a Time

The loop variable changes as the loop progresses. On the first iteration, it holds the first list element. On the next iteration, it holds the second element. This continues until every element has been processed. The loop body runs once with each current value.

friends["Ava", "Ben", "Kai"]Avacurrent valueBencurrent valueKaicurrent valuefirst elementnext iterationnext iteration
What happens next as the loop moves from one list element to the next?
python
Output
Hello, Ava
Hello, Ben
Hello, Kai

Reading the Loop Syntax

In the pattern for friend in friends, friends is the list being processed and friend is the loop variable. The loop variable name is chosen by the programmer. Names such as friend, name, or person describe the current element more clearly than a short name such as f.

Position 1AvafriendAvaPosition 2BenfriendBenPosition 3KaifriendKaicurrent valuecurrent valuecurrent value
How does each position in the list map to the current value of the loop variable?
Best practice

Choose a descriptive loop variable. for friend in friends communicates the purpose of the loop more clearly than for f in friends, even though both versions work in the same way.

Inside and After the Loop

Indentation determines which statements belong to the loop body. A line indented under the for statement runs once for every element. A line at the original indentation level runs after the loop has completed all its iterations.

names["Ava", "Ben", "Kai"]Current nameone list elementPrint greetingindented loop bodyPrint completeafter the looptake next elementrun oncerepeatall elements processed
Which statements run once per element, and which statement waits until the loop finishes?
python
Output
Hello, Ava
Hello, Ben
Hello, Kai
All greetings are complete.

Tracing Each Iteration

What do you think happens?

What will this code print, and how many times will the indented print statement run?

colors = ["red", "blue"]

for color in colors:
    print("Color: " + color)

print("Finished")

  • Color: red, Color: blue, Finished

  • Color: red, Color: blue, Color: Finished

  • Finished only

Reveal answer
Answer:

Color: redColor: blueFinished

The loop variable color first holds red and then blue, so the indented statement runs twice. The unindented Finished statement runs once after both iterations.

colors["red", "blue"]color = redColor: redcolor = blueColor: blueFinishedafter the loopfirst elementnext elementloop complete
What value does the loop variable have on each iteration, and what output is produced at each step?

To trace a for loop, make a short record for each element. First record the loop variable's value, then determine what the indented statements do with that value. After the final element, move to the unindented statements and run them once.

Mistakes Beginners Make

  • Common mistake

    Forgetting to indent the loop body

    What it looks like
    for name in names:
    print(name)
    Why it fails

    The statement intended to run for each element is not visibly placed under the for statement.

    Do this instead
    Indent the statement so it belongs to the loop body:
    for name in names:
        print(name)
  • Common mistake

    Indenting code that should run after the loop

    What it looks like
    for name in names:
        print(name)
        print("Finished")
    Why it fails

    Finished is indented, so it runs once for every element rather than once after the loop.

    Do this instead

    Place the final statement at the original indentation level.

  • Common mistake

    Using the wrong variable name inside the loop

    What it looks like
    for name in names:
        print(friend)
    Why it fails

    The loop variable is name, but the loop body tries to use friend.

    Do this instead

    Use the same loop variable inside the body: print(name).

Practice the Trace

EASY

Given the code below, write the output in order. Then state the value of item during each iteration and identify which line runs only after the loop.

items = ["book", "pen", "map"]

for item in items:
    print("Item: " + item)

print("List complete")

Hints
  • The loop variable takes the first, second, and third list values in sequence.
  • The indented print statement runs once for each of the three elements.
  • The final print statement is unindented.
Key point

A reliable trace follows this order: choose the next list element, assign its value to the loop variable, run the indented body, and repeat until no elements remain. Then run the code after the loop.

What to Remember

  1. 1
    A for loop executes its body once for each element in a list.
  2. 2
    The loop variable holds the current element and changes on each iteration.
  3. 3
    Indented statements belong to the loop body and run once per element.
  4. 4
    Unindented statements after the loop run when all elements have been processed.
  5. 5
    Descriptive loop variable names and careful tracing make loops easier to understand.

At a glance

  • A for loop processes every list element sequentially.
  • The loop variable represents the current element during each iteration.
  • Indentation separates repeated loop work from code that runs after the loop.
  • Tracing the current value and the loop body lets you predict the output.
  • Descriptive variable names improve readability and make the loop's purpose clear.

Related concepts

More concepts starting with L