Skip to main content

Section 9.10 Traversal and the for Loop: By Item

A lot of computations involve processing a collection one item at a time. For strings this means that we would like to process one character at a time. Often we start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal.
We have previously seen that the for statement can iterate over the items of a sequence (a list of names in the case below).
Recall that the loop variable takes on each value in the sequence of names. The body is performed once for each name. The same was true for the sequence of integers created by the range function.
Since a string is simply a sequence of characters, the for loop iterates over each character automatically.
The loop variable achar is automatically reassigned each character in the string “Go Spot Go”. We will refer to this type of sequence iteration as iteration by item. Note that it is only possible to process the characters one at a time from left to right.
Check your understanding

Checkpoint 9.10.1.

    How many times is the word HELLO printed by the following statements?
    s = "python rocks"
    for ch in s:
  • 10
  • Iteration by item will process once for each item in the sequence.
  • 11
  • The blank is part of the sequence.
  • 12
  • Yes, there are 12 characters, including the blank.
  • Error, the for statement needs to use the range function.
  • The for statement can iterate over a sequence item by item.

Checkpoint 9.10.2.

    How many times is the word HELLO printed by the following statements?
    s = "python rocks"
    for ch in s[3:8]:
  • 4
  • Slice returns a sequence that can be iterated over.
  • 5
  • Yes, The blank is part of the sequence returned by slice
  • 6
  • Check the result of s[3:8]. It does not include the item at index 8.
  • Error, the for statement cannot use slice.
  • Slice returns a sequence.
You have attempted of activities on this page.