Skip to main content

Section 7.13 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 following case).
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 a sequence of characters, a for loop will automatically iterate over each character.
The loop variable a_char is automatically reassigned each character in the string "playground". 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 when using this form of traversal.

Checkpoint 7.13.1.

    How many characters will be printed by the following statements?
    s = "python rocks"
    for ch in s:
        print(ch.upper())
    
  • 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 7.13.2.

    How many lines are printed by the following statements?
    s = "python rocks"
    for ch in s[3:8]:
        print(ch)
    
  • 4
  • Blanks are characters too; for doesn’t skip over them.
  • 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, and for can process sequences.