Concepts / Accumulator Patterns with Strings

Accumulator Patterns with Strings

Traversal is the process of handling a string one character at a time, from beginning to end.

  • Programming

Following Characters in Order

Suppose you want to process every character in a string from left to right. The key question is not only which character you are handling now, but also how you know when there are no characters left. Traversal is the pattern for handling a string one character at a time, from beginning to end. A while loop makes the control of that process visible: an index identifies the current position, a condition checks whether that position is valid, and an update moves to the next position.

A correct traversal visits each character exactly once, in order, and stops when the index reaches the string's length.

Mapping Indices to Characters

String positions begin at index 0. For the string banana, index 0 refers to b, index 1 refers to a, and the remaining characters continue in order through index 5. Because the string has length 6, the valid indices are 0, 1, 2, 3, 4, and 5. The final valid index is always len(string) - 1. The value len(string) itself is not a character position.

nextnextnextnextnextnext0b1a2n3a4n5a6length
Which character does the loop process at each index, and what happens when the index reaches the string's length?

The Three-Part While Pattern

A string traversal with a while loop has three essential pieces. First, set index to 0 so the traversal starts at the first character. Second, continue while index is less than the string's length. Third, increase index by 1 after processing the current character. Inside the loop, fruit[index] retrieves the character at the current position. The condition is checked before each iteration, so the loop stops before trying to access the position equal to the string's length.

python
begintrueprocessrepeatfalseindex = 0index < len(fruit)fruit[index]index + 1Stop
In what order does the loop check its condition, process a character, update the index, and repeat or stop?

Tracing a Complete Run

What do you think happens?

What characters will this traversal print, and in what order? fruit = "banana" index = 0 while index < len(fruit): print(fruit[index]) index = index + 1

  • b, a, n, a, n, a
  • a, b, a, n, a, n
  • b, a, n, a, n, a, followed by an error
  • Only b
Reveal answer

Answer: b, a, n, a, n, a

The string length is 6, so the condition is true for indices 0 through 5. After index becomes 6, index < len(fruit) is false and the loop stops before fruit[6] is accessed.

index + 1index + 1index + 1index + 1index + 1index + 1Step 0index 0; b; output bStep 1index 1; a; output baStep 2index 2; n; output banStep 3index 3; a; output banaStep 4index 4; n; output bananStep 5index 5; a; output bananaStopindex 6; condition false
How do the index, current character, and output change after each iteration?
Output
b
a
n
a
n
a

Reading the final iteration

Explain what happens when the traversal reaches the last character of banana.

Current position: The index is 5, which is the final valid index because len(banana) is 6 and the last index is len(banana) - 1.

Character access: fruit[index] accesses fruit[5], which is the final a in banana.

Index update: After processing that character, index increases from 5 to 6.

Loop check: The condition 6 < 6 is false, so the loop stops before attempting to access fruit[6].

Every character is processed once, and the traversal stops safely when the index reaches the string's length.

Building an Accumulated String

Traversal does not have to print each character immediately. The same index pattern can process a character and add it to an accumulated string. The important traversal mechanism stays the same: begin at index 0, check that the index is within the string, process the character at that index, and increment the index. In this way, the accumulated result grows as the loop visits the characters in order.

python
add cadd aadd tresultemptyresultcresultcresultcaresultcaresultcat
How does the accumulated string change when each new character is added during traversal?

Preventing Boundary Errors

ConditionWhen index reaches the lengthResult
index < len(fruit)The condition is falseThe loop stops before an invalid access
index <= len(fruit)The condition is still trueThe loop tries to access an index that does not exist
false at lengthtrue at lengthindex < len(fruit)index = lengthstopindex <= len(fruit)index = lengthinvalid access
What is the difference between stopping when the index is less than the string length and incorrectly allowing the index to equal the length?
  • Using index <= len(fruit) as the loop condition.

    When index equals the string's length, the condition still allows the loop body to run. That index is not a valid character position.

    Fix: Use index < len(fruit) so the loop stops before the index reaches the invalid position.

  • Forgetting to increment the index.

    The index stays at the same position, so the traversal does not move to the next character.

    Fix: Increment index by 1 after processing the current character.

  • Starting at index 1.

    The traversal skips the character at index 0, which is the first character.

    Fix: Start the index at 0.

Practice the Pattern

EASY

Trace this loop without running it. Record the index and character for every iteration, then state the value of index when the loop stops. word = "code" index = 0 while index < len(word): print(word[index]) index = index + 1

Hints
  • The valid indices run from 0 through len(word) - 1.
  • The string code has four characters.
  • The stopping index is the first value that makes index < len(word) false.

Checking the trace

Trace the traversal of code.

Iteration 1: index is 0, so word[index] is c. Afterward, index becomes 1.

Iteration 2: index is 1, so word[index] is o. Afterward, index becomes 2.

Iteration 3: index is 2, so word[index] is d. Afterward, index becomes 3.

Iteration 4: index is 3, so word[index] is e. Afterward, index becomes 4.

Stopping check: The string length is 4. At index 4, the condition 4 < 4 is false, so the loop stops.

The output is c, o, d, e, and the final index is 4.

Traversal Checklist

  1. Traversal processes a string one character at a time from beginning to end.
  2. Start the index at 0 because indexing begins with the first character at position 0.
  3. Use index < len(string) so every valid index is processed and the index equal to the length is not accessed.
  4. Process string[index], then increment the index by 1 to move forward.
  5. For debugging, check that the loop visits indices 0 through len(string) - 1 and stops when the index reaches len(string).

Key Takeaways

  • Traversal is the process of handling a string one character at a time in order.
  • A while-loop traversal uses an index initialized to 0, a bounds check, and an increment of 1.
  • The valid indices of a string end at len(string) - 1.
  • The condition index < len(string) prevents an invalid access when index reaches the string's length.
  • Tracing the index, current character, and accumulated output exposes off-by-one and update errors.