# 7.7. Traversal and the for Loop: By Index¶

It is also possible to iterate through the indexes of a string or sequence. 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. We can use Enumerate, a built-in Python function, to make this process easier because it allows us to loop through something and have an automatic counter.

By using the enumerate function, we can print out a counter that tells us the position of an item in a list. We could do this ourselves, but this saves us from having to do that. The index positions in the list are 0, 1 , 2, 3, and 4. This is exactly the same sequence of integers that are stored in counter each time the loop is iterated. The first time through the for loop, counter will be 0 and “apple” will be printed. Then, counter will be reassigned to 1 and “pear” will be displayed. This will continue until the list has ended, so that the final value for counter will be 4 and the final value of item will be “peach”.

Conveniently, we can also use the range function to automatically generate the indices 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.

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.

(clens14_6_2)

moreiter-6-1: How many times is the letter p printed by the following statements?

s = "python"
for idx in range(len(s)):
print(s[idx % 2])

• 0
• idx % 2 is 0 whenever idx is even
• 1
• idx % 2 is 0 whenever idx is even
• 2
• idx % 2 is 0 whenever idx is even
• 3
• idx % 2 is 0 whenever idx is even
• 6
• idx % 2 is 0 whenever idx is even
Next Section - 7.8. Nested Iteration: Image Processing