9.6. Traversal and the for
Loop: By Index¶
It is possible to use the range
function to systematically
generate the indices of the characters. The for
loop can then be
used to iterate over these positions. These positions can be used
together with the indexing operator to access the individual
characters in the string.
Consider the following codelens example.
Python 3.3
Step 1 of 19 line that has just executed next line to execute Visualized using Online Python Tutor by Philip Guo |
| |||||||||||||||
(ch08_7)
The index positions in “apple” are 0,1,2,3 and 4. This is exactly the
same sequence of integers returned by range(5)
. The first time
through the for loop, i
will be 0 and the “a” will be printed.
Then, i
will be reassigned to 1 and “p” will be displayed. This
will repeat for all the range values up to but not including 5. Since
“e” has index 4, this will be exactly right to show all of the
characters.
In order to make the iteration more general, we can use the len
function to provide the bound for range
. This is a very common
pattern for traversing any sequence by position. Make sure you
understand why the range function behaves correctly when using len
of the string as its parameter value.
fruit: str
i: int
fruit = "apple"
for i in range(0, len(fruit), 1):
print(fruit[i])
(ch08_7b)
You may also note that iteration by position allows the programmer to control the direction of the traversal by changing the sequence of index values. Recall that we can create ranges that count down as well as up so the following code will print the characters from right to left.
Python 3.3
Step 1 of 14 line that has just executed next line to execute Visualized using Online Python Tutor by Philip Guo |
| |||||||||||||
(ch08_8)
Trace the values of i
and satisfy yourself that they are correct.
In particular, note the start and end of the range.
Check your understanding
strings-11-1: How many times is the letter o printed by the following statements?
s: str
s = "python rocks"
for i in range(len(s)):
if i % 2 == 0:
print(s[i])