9.11.7. Loops and Lists#
9.11.7.1. for Statements#
The for
statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers, or giving the user the ability to define both the iteration step and halting condition, Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example:
1# Measure some strings:
2words = ['cat', 'window', 'defenestrate']
3
4for w in words:
5 print(w, len(w))
cat 3
window 6
defenestrate 12
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:
1for w in words[:]: # Loop over a slice copy of the entire list.
2 if len(w) > 6:
3 words.insert(0, w)
4words
['defenestrate', 'cat', 'window', 'defenestrate']
9.11.7.2. 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:
1for i in range(5):
2 print(i)
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’):
1range(5, 10) # 5 through 9
2range(0, 10, 3) # 0, 3, 6, 9
3range(-10, -100, -30) # -10, -40, -70
To iterate over the indices of a sequence, you can combine range()
and len()
as follows:
1a = ['Mary', 'had', 'a', 'little', 'lamb']
2for i in range(len(a)):
3 print(i, a[i])
0 Mary
1 had
2 a
3 little
4 lamb
In most such cases, however, it is convenient to use the enumerate()
function.
9.11.7.3. break and continue Statements, and else Clauses on Loops#
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
Loop statements may have an else
clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
1for n in range(2, 10):
2 for x in range(2, n):
3 if n % x == 0:
4 print(n, 'equals', x, '*', n//x)
5 break
6 else:
7 # loop fell through without finding a factor
8 print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
When used with a loop, the else
clause has more in common with the else
clause of a try statement than it does that of if statements: a try statement’s else
clause runs when no exception occurs, and a loop’s else
clause runs when no break
occurs. For more on the try statement and exceptions.
The continue statement continues with the next iteration of the loop:
1for num in range(2, 10):
2 if num % 2 == 0:
3 print("Found an even number", num)
4 continue
5 print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9