Concepts / Iterating Over Strings with for Loops

Iterating Over Strings with for Loops

A for loop executes a block of code once for each element in a list, with the loop variable taking on each element's value in sequence.

  • Programming

One Instruction, Many Characters

Suppose you want to display every character in a word. You could handle each character separately, but a for loop lets you write the processing instruction once and run it for every character. When Python traverses a string with a for loop, it automatically assigns one character at a time to a loop variable.

python
Output
b
a
n
a
n
a

What do you think happens?

Before reading the explanation, predict how many times print(char) runs and what char contains on the first and last iterations.

Reveal answer

Answer: print(char) runs six times. char contains b on the first iteration and a on the last iteration.

The string banana has six characters. The loop visits them in order, assigning one character to char during each iteration.

Positions Become Iterations

The string banana contains six characters. Their positions correspond to the order in which the loop receives them: b first, then a, then n, then a, then n, then a. The loop variable receives the character itself rather than displaying the position number. You do not manually write an index, increment a counter, or check whether the end of the string has been reached.

nextnextnextnextnext0b1a2n3a4n5a
How does each position in banana correspond to the character received by the loop?

A for loop is simpler and more readable than manually traversing a string with a while loop and index tracking. The loop makes the intention clear: visit every character in order. It also avoids having to remember to increment an index or check whether the end of the string has been reached.

Following the Loop Variable

To trace a loop, record the loop variable's value at every iteration and then record what the loop body does with that value. In the example below, char is reassigned as control moves through fruit. It does not keep all the characters at once; it holds the current character for the current iteration.

next characternext characternext characternext characternext characterIteration 1char = b; output bIteration 2char = a; output aIteration 3char = n; output nIteration 4char = a; output aIteration 5char = n; output nIteration 6char = a; output a
What character does char contain at each iteration, and what output is produced?

Adding a Message Around Each Character

Trace what happens when each character in the string code is printed with a label.

First iteration: char receives c. The loop body prints Character: c.

Second iteration: char receives o. The loop body prints Character: o.

Third iteration: char receives d. The loop body prints Character: d.

Fourth iteration: char receives e. The loop body prints Character: e.

After the loop: All four characters have been visited, so execution continues with the next unindented statement.

The loop body runs four times, once for each character, in the order c, o, d, e.

python
Output
Character: c
Character: o
Character: d
Character: e
Finished

Inside and After the Loop

Indentation determines which statements belong to the loop body. A statement indented under the for statement runs once for every character. A statement at the original indentation level runs after the loop has processed all characters. This difference controls whether an action repeats or happens only once.

yesnoStartNext characterassign to charLoop bodyruns once per characterMore charactersAfter-loop statementruns onceEnd
Which statements run once per character, and which statement runs only after every character has been processed?

Naming the Current Character

The loop variable name is arbitrary. In a string loop, names such as char or letter can indicate that the variable holds one character. A descriptive name makes the loop self-documenting. A short name may work, but it gives the reader less information about the value being processed.

Loop formValue received by the loop variableReadability
for char in fruitOne character from fruitDescriptive
for letter in fruitOne character from fruitDescriptive
for f in fruitOne character from fruitLess clear
python

Mistakes During Traversal

  • Forgetting to indent the loop body.

    The statement intended to run for each character is not indented under the for statement.

    Fix: Indent the loop body so Python can identify it as part of the loop.

  • Indenting code that should run after the loop.

    Finished is inside the loop, so it runs once per character rather than once after all characters.

    Fix: Place the final print statement at the original indentation level.

  • Using the wrong variable name inside the loop.

    The loop assigns characters to char, not letter.

    Fix: Use the same loop variable name in the body, such as print(char).

  • Expecting the loop variable to contain an index number.

    A string loop gives the loop variable each character directly. It does not display the position number.

    Fix: Treat char as the current character and trace the characters in their string order.

Repeated characters are still visited separately. In banana, the loop receives a, n, and a at different iterations. The loop does not remove or skip a character merely because the same character appeared earlier.

When the output differs from your expectation, write the string's characters in order and place one character beside each iteration. Then check three points: whether every character appears in the expected order, whether the loop variable name matches the name used in the body, and whether each statement has the intended indentation.

Practice the Trace

EASY

Write a for loop that traverses the string "lamp". For each character, print the text "Current:" followed by the character. Then print "All done" only after the loop completes.

Hints
  • Use a descriptive loop variable such as char.
  • Place the repeated print statement inside the loop.
  • Place the final print statement at the original indentation level.
MEDIUM

Trace this loop without running it. Write the value of letter and the output produced on each iteration: word = "tree"; for letter in word: print(letter). Then explain why the repeated e characters produce two separate iterations.

Hints
  • List the characters from left to right.
  • The loop variable receives one character during each iteration.
  • Repeated characters remain separate positions in the traversal.

A reliable trace follows the same pattern every time: identify the next character, assign it mentally to the loop variable, execute the indented body, and then move to the next character. After the final character, stop repeating the indented body and continue with the unindented code.

Key Takeaways

  1. A for loop over a string assigns each character to its loop variable in sequence.
  2. The loop body runs once for every character, while unindented code runs after the loop completes.
  3. Tracing the loop variable step by step helps you predict output and locate unexpected behavior.
  4. The loop variable name can be chosen freely, but a descriptive name makes the code easier to understand.
  5. A for loop handles the traversal automatically, so manual index tracking is not required.

Key Takeaways

  • A string for loop visits characters from first to last.
  • The loop variable holds the current character and changes on each iteration.
  • Indentation separates repeated loop-body work from work that happens after the loop.
  • Tracing each character and output is an effective way to predict results and debug loops.
  • Descriptive loop variable names improve readability.