10.17. Lists and for
loops¶
It is also possible to perform list traversal using iteration by item as well as iteration by index.
fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits: # by item
print(afruit)
(chp09_03a)
It almost reads like natural language: For (every) fruit in (the list of) fruits, print (the name of the) fruit.
We can also use the indices to access the items in an iterative fashion.
fruits = ["apple", "orange", "banana", "cherry"]
for position in range(len(fruits)): # by index
print(fruits[position])
(chp09_03b)
In this example, each time through the loop, the variable position
is used as an index into the
list, printing the position
-eth element. Note that we used len
as the upper bound on the range
so that we can iterate correctly no matter how many items are in the list.
Any sequence expression can be used in a for
loop. For example, the range
function returns a sequence of integers.
for number in range(20):
if number % 3 == 0:
print(number)
(chp09_for3)
This example prints all the multiples of 3 between 0 and 19.
Since lists are mutable, it is often desirable to traverse a list, modifying
each of its elements as you go. The following code squares all the numbers from 1
to
5
using iteration by position.
numbers = [1, 2, 3, 4, 5]
print(numbers)
for i in range(len(numbers)):
numbers[i] = numbers[i] ** 2
print(numbers)
(chp09_for4)
Take a moment to think about range(len(numbers))
until you understand how
it works. We are interested here in both the value and its index within the
list, so that we can assign a new value to it.
Check your understanding
list-17-1: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = [ ]
for item in alist:
blist.append(item+5)
print(blist)