The for loop and range
Going through a sequence and a range of numbers.
for takes the elements of a sequence one at a time and runs the block for each:
for letter in "cat":
print(letter)
You can loop over strings, lists, dictionaries and anything else Python can hand out one element at a time. There is no need to keep a counter by hand: the loop knows when the elements run out.
For repeating over numbers there is range:
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 10, 3))) # [2, 5, 8]
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]
As with slices, the end is not included: range(1, 5) is four numbers, from 1 to 4. The step can be negative. range does not build a list in memory, it hands out numbers on demand, so range(1_000_000) costs nothing.
A typical pattern is accumulating a result:
total = 0
for n in range(1, 101):
total += n
print(total) # 5050
break and continue work in for the same way as in while. Do not change the list you are looping over: removing elements on the fly shifts the indexes, and the loop skips elements. If you need to filter, build a new list.
Practice
A range with a step
What does the program print?
print(list(range(2, 10, 3)))Properties of range
Mark the true statements about range.
- range(5) starts at 0
- The end of the range is not included
- range(1, 5) has five numbers
- The step can be negative
Vowels
Write a function count_vowels(text) that counts the Latin vowels a, e, i, o, u in a string, ignoring case.