Computer Science · Ch 9 — Lists
Traversing a List
Traversing a List
Traversing a list means visiting each of its elements, one after another — usually to print, examine or process them. Python offers two loop constructs for this: the for loop and the while loop.
(A) List traversal using a for loop
The most direct way is to loop over the list itself. The loop variable takes on each element in turn:
>>> planets = ['Mercury', 'Venus', 'Earth', 'Mars']
>>> for item in planets:
... print(item)
Output:
Mercury
Venus
Earth
Mars
The range() and len() variant
Another way to reach the elements is to loop over the indices instead, generated by combining the range() and len() functions. len(planets) gives the number of elements, range() turns that into the index sequence 0, 1, 2, …, and each element is then fetched by indexing:
>>> for i in range(len(planets)):
... print(planets[i])
Output:
Mercury
Venus
Earth
Mars
Both forms visit every element in order. The index-based form is the one to choose when you also need the position i — for instance, to modify planets[i] while traversing (this is exactly how the function in Section 9.7 increments every element of a list).
(B) List traversal using a while loop
A while loop achieves the same traversal with explicit index management: initialise a counter to 0, loop while it is smaller than the list's length, and advance it manually each pass:
>>> planets = ['Mercury', 'Venus', 'Earth', 'Mars']
>>> i = 0
>>> while i < len(planets):
... print(planets[i])
... i += 1
Output:
Mercury
Venus
Earth
Mars
``` …