Part 03 / Topic 7 of 12
range(start, stop, step)
range makes a sequence of numbers, like the numbered tokens at a bank counter. stop is not included.
| Call | Numbers |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(0, 11, 5) |
0, 5, 10 |
range(5, 0, -1) |
5, 4, 3, 2, 1 |
Real-world example: a times table and a rocket countdown.
for i in range(1, 4):
print(f"7 x {i} = {7 * i}")
# 7 x 1 = 7
# 7 x 2 = 14
# 7 x 3 = 21
print(list(range(10, 0, -3))) # [10, 7, 4, 1]
๐ Going deeper:
rangedoes not build all the numbers in memory. It works them out when asked, sorange(1_000_000_000)is instant and tiny. Wrap it inlist()only when you want to see the numbers.
Done here? The practice set for Part 3 โ 7 exercises with solutions โ is on the part page.