Python The range() Function
The range() function is a function that builds a counting sequence. A for loop can walk that sequence.
range with one value
One value is the stop point. It is not included.
print(list(range(5)))range with start and stop
The count starts at 2 and stops before 6.
print(list(range(2, 6)))range with a step
A step of 2 skips every second number.
print(list(range(1, 10, 2)))Count down with a negative step
A step of -1 counts down. The stop value is still not included.
print(list(range(5, 0, -1)))Example
for number in range(0, 21, 2):
print(number)Key points
- Use range(stop) to count from 0 up to, but not including, stop.
- Use range(start, stop) to start at a chosen value.
- Use range(start, stop, step) to choose the step size.
- range() builds the counting sequence that a for loop walks.
- Step: how much the count changes each time.
- A negative step counts down.
- Use list(range(...)) to see all the values at once.
In this example, range starts at 0. It stops before 21, so 20 is the last value. The step is 2. The loop prints each even number in turn. It prints 0, then 2, and so on up to 20.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does list(range(3, 7)) give?