In this chapter, we will present iteration using loops and iterators. We will show examples of how this can be used with lists and generators. Iteration is one of the fundamental operations a computer is useful for. Traditionally, iteration is achieved by a for
loop. A for
loop is a repetition of a block of instructions a certain number of times. Inside the loop, one has access to a loop variable, in which the iteration number is stored.
The Python idiom is slightly different. A for
loop in Python is primarily designed to exhaust a list, that is, to enumerate the elements of a list. The effect is similar to the repetition effect just described if one uses a list containing the first n integers.
A for
loop only needs one element of the list at a time. It is therefore desirable to use a for
loop with objects that are able to create those elements on demand, one at a time. This is what iterators achieve in Python.
The primary aim of the for
statement is to traverse a list:
for s in ['a', 'b', 'c']: print(s), # a b c
In this example, the loop variable s is successively assigned to one element of the list. Notice that the loop variable is available after the loop has terminated. This may sometimes be useful; refer, for instance, the example in section Controlling the flow inside the loop.
One of the most frequent uses of a for
loop is to repeat a given task a defined number of times, using the function range
(refer to section Lists of Chapter 1, Getting Started).
for iteration in range(n): # repeat the following code n times ...
If the purpose of a loop is to go through a list, many languages (including Python) offer the following pattern:
for k in range(...): ... element = my_list[k]
If the purpose of that code were to go through the list my_list
, the preceding code would not make it very clear. For this reason, a better way to express this is as follows:
for element in my_list: ...
It is now clear at first glance that the preceding piece of code goes through the my_list
list. Note that if you really need the index variable k, you may replace the preceding code by this:
for k, element in enumerate(my_list): ...
The intent of this piece of code is to go through my_list
while keeping the index variable k available. A similar construction for arrays is the command ndenumerate
.
18.188.61.81