Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Traversing a List
Traversing a List
Creating a list is only half the story — most programs need to visit every element of a list one after another, whether to display them, add them up, or test each one against a condition. Visiting each element of a list in order is called traversing the list, and Python offers two loop constructs for it: the for loop and the while loop.
Traversal with a for loop — directly over the elements
The most natural way is to let the for loop hand you each element of the list, one per iteration. The loop variable takes the value of the first element, the body runs, then the variable takes the second element, and so on until the list is exhausted.
>>> list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Here item is just a loop variable — in the first pass it holds 'Red', in the second 'Green', and so on. You never deal with index numbers at all; Python fetches the elements for you in order.
Traversal using range() and len()
The second style reaches each element through its index. Two built-in functions work together here:
len(list1)returns the length of the list — the total number of elements it contains. For the five-colour list above it returns 5.range(n)produces a sequence of numbers starting at 0, increasing by 1, and stopping at n − 1 — that is, one number less than the value given. Sorange(5)yields 0, 1, 2, 3, 4.
Combining the two, range(len(list1)) generates exactly the set of valid indices of the list. The loop variable i then runs through those indices, and list1[i] picks out the element at each position:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
The output is identical to the first method; the difference is only in how each element is reached. In the first form the loop variable is the element; in the second form the loop variable is the index, and the element is obtained by subscripting the list with it. The index-based form is handy whenever the position of the element matters to you as well as its value, since i is available inside the loop. …