Page 26 - Python Tutorial
P. 26

Python Tutorial, Release 3.7.0

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate
selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly
make a copy. The slice notation makes this especially convenient:

>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over
and over again.

4.3 The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions:

>>> for i in range(5):
... print(i)
...
0
1
2
3
4

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices
for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a
different increment (even negative; sometimes this is called the ‘step’):

range(5, 10)
    5, 6, 7, 8, 9

range(0, 10, 3)
    0, 3, 6, 9

range(-10, -100, -30)
   -10, -40, -70

To iterate over the indices of a sequence, you can combine range() and len() as follows:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.
A strange thing happens if you just print a range:

20 Chapter 4. More Control Flow Tools
   21   22   23   24   25   26   27   28   29   30   31