Algorithmsiteration over string

Iteration Over a String (Indices, enumerate, neighbors)

TT
Testlaa Team
May 14, 20261 min read

Iteration visits each character in order—for ch in s—or with indices via range(len(s)) / enumerate. Choosing style communicates intent and avoids off-by-one bugs.

Why this shows up in the real world

Screen readers stream text character by character with prosody rules. Diff tools align two files by walking both strings with coordinated indices.

Core idea (explained for students)

Use enumerate when you need previous/next context: for i,ch in enumerate(s): left = s[i-1] if i else ''. For reverse iteration, for ch in reversed(s) or negative stepping.

Try this in Python

def with_neighbors(s: str) -> list[tuple[str | None, str, str | None]]:
    n = len(s)
    return [
        (s[i - 1] if i else None, s[i], s[i + 1] if i + 1 < n else None) for i in range(n)
    ]


print(with_neighbors("ab"))

Common mistakes

  • Modifying index while looping forward—classic skip bugs; iterate on a copy or use while loops carefully.
  • for i in range(len(s)) when values not needed—prefer direct char iteration.

Key takeaways

  • enumerate is default when you need both index and character.
  • Pair with zip for parallel string walks.

Tags:

StringsPythonStudents