Concepts / For Loops and String Traversal

For Loops and String Traversal

The final character is at index len(string) - 1. For 'banana', that final valid index is 5, because the string length is 6.

  • Programming

One Character at a Time

Traversal is the process of handling a string one character at a time, from beginning to end. Instead of treating the string as one undivided value, a traversal moves through its positions in order and processes the character found at each position.

A while loop provides a clear way to express this pattern. The loop keeps track of an index, uses that index to access one character, and then moves the index forward. The same structure can be used whenever a task needs to examine every character in sequence.

Indexing the String

String positions begin at index 0. For the string 'banana', index 0 gives 'b', index 1 gives 'a', and the remaining characters follow at later indices. Because 'banana' has length 6, its valid indices are 0, 1, 2, 3, 4, and 5.

0b1a2n3a4n5anext indexnext indexnext indexnext indexnext index
Which character is accessed at each index as traversal moves through the string?
Key point

The final character is at index len(string) - 1. For 'banana', that final valid index is 5, because the string length is 6.

The Three-Part Loop

A traversal while loop has three essential pieces. First, the index starts at 0 so the loop begins with the first character. Second, the condition checks whether the index is still less than the string's length. Third, the index increases by 1 after the current character is accessed. Together, these pieces visit every character once, in order, and stop at the end.

Code walkthrough
fruit = 'banana'
index = 0
while index < len(fruit):
    print(fruit[index])
    index += 1
  1. 1
    index = 0 starts the traversal at the first character.
  2. 2
    index < len(fruit) checks whether the current index is valid for another access.
  3. 3
    print(fruit[index]) processes the character at that position by printing it.
  4. 4
    index += 1 moves to the next position.
  • The string being traversed is assigned to fruit.
  • The index starts at 0, the first position.
  • The loop continues only while index is less than the string length.
  • fruit[index] accesses the character at the current position.
  • The index increases by 1 after each iteration.
index < len(fruit)fruit[index]access characterindex += 1move forwardStopindex equals lengthtruethencheck againfalse
How does the condition determine whether another character is visited or the loop stops?

Tracing Banana

What do you think happens?

What will this traversal print, and in what order?

  • banana

  • ananab

  • 012345

  • It will print nothing

Reveal answer
Answer:

It prints b, a, n, a, n, and a on separate lines, in that order.

The index starts at 0 and advances by 1 after each character is accessed. The valid indices for 'banana' are 0 through 5, so the characters are visited from beginning to end.

python
Output
b
a
n
a
n
a
index 0b; output bindex 1a; output aindex 2n; output nindex 3a; output aindex 4n; output nindex 5a; output aindex 6condition falseincrementincrementincrementincrementincrementincrement
What happens to the index, accessed character, and output on each iteration?
Index before iterationCharacter accessedOutputIndex after increment
0bb1
1aa2
2nn3
3aa4
4nn5
5aa6

Trace of the traversal through 'banana'. After index becomes 6, index < len(fruit) is false because the length is 6.

Boundary Mistakes

  • Common mistake

    Using index <= len(fruit) as the loop condition.

    What it looks like
    while index <= len(fruit):
    Why it fails

    When index reaches the string's length, the condition is still true. The loop then tries to access fruit[index], but that index does not exist.

    Do this instead

    Use index < len(fruit). The last valid index is len(fruit) - 1.

  • Common mistake

    Starting the index at 1.

    What it looks like
    index = 1
    Why it fails

    The traversal does not begin at the first character, whose index is 0.

    Do this instead

    Start with index = 0 when the goal is to visit every character from the beginning.

  • Common mistake

    Forgetting to increment the index.

    What it looks like
    while index < len(fruit):
        print(fruit[index])
    Why it fails

    The index does not move to the next position, so the traversal cannot progress through the string.

    Do this instead

    Increment the index after processing the current character with index += 1.

index < len(fruit)valid indices 0 through 5index 6condition falseindex <= len(fruit)allows index 6fruit[6]index does not existfalse at 6true at 6
What changes when the loop continues until an index equal to the string length?
Best practice

When debugging a traversal, write down the index before each iteration. Check three questions in order: Is the index at the intended starting position? Is the condition true for the current position? Will the increment move to the next position or past the boundary?

Trace It Yourself

EASY

Trace the loop below. Record the character accessed at each index and the index value when the loop stops.

Hints
  • The string has length 6.
  • The first index is 0.
  • The loop condition is false when index reaches 6.
python
Worked example

Checking the Final Iteration

What happens when the index is 5, and what happens after the increment?

  1. 1
    Access

    Index 5 identifies the final character of 'banana', which is 'a'.

  2. 2
    Increment

    After the character is printed, index increases from 5 to 6.

  3. 3
    Condition check

    The string length is 6, so index < len(fruit) becomes 6 < 6, which is false.

Result

The final character is visited, and then the loop stops without attempting to access index 6.

Traversal Checklist

  1. 1
    Traversal handles a string one character at a time from beginning to end.
  2. 2
    A while-loop traversal starts its index at 0, accesses the character at that index, and increments the index by 1.
  3. 3
    The condition index < len(fruit) allows valid indices and stops when the index reaches the string length.
  4. 4
    For a string of length 6, the valid indices are 0 through 5, and the final character is at index len(fruit) - 1.
  5. 5
    To debug a traversal, trace the index, the accessed character, the condition, and the increment at every iteration.

Key Takeaways

  • Traversal means processing a string one character at a time in order.
  • The standard while-loop pattern uses an index that starts at 0, a bounds check using index < len(string), and an increment of 1.
  • The final valid index is len(string) - 1; the index equal to the string length is the stopping point, not a character position.
  • Off-by-one errors commonly come from using <= instead of <, starting at the wrong index, or failing to increment.

More concepts starting with F