Skip to main content

Section 4.11 Traversal and the for Loop: By Index

With a for loop, the loop variable is bound, on each iteration, to the next item in a sequence. Sometimes, it is natural to think about iterating through the positions, or indexes of a sequence, rather than through the items themselves.
For example, consider the list ['apple', 'pear', 'apricot', 'cherry', 'peach']. β€˜apple’ is at position 0, β€˜pear’ at position 1, and β€˜peach’ at position 4.
Thus, we can iterate through the indexes by generating a sequence of them, using the range function.
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 list as its parameter value.
In some other programming languages, that’s the only way to iterate through a sequence, by iterating through the positions and extracting the items at each of the positions. Python code is often easier to read because we don’t have to do iteration that way. Compare the iteration above with the more β€œpythonic” approach below.
If we really want to print the indexes (positions) along with the fruit names, then iterating through the indexes as in the previous versions is available to us. Python also provides an enumerate function which provides a more β€œpythonic” way of enumerating the items in a list, but we won’t cover that in this introductory course.
Check your understanding

Checkpoint 4.11.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
You have attempted of activities on this page.