Python range() Function: Syntax, Examples & Practice Programs
Python range() Function
What is the purpose of range()?
The range() function in Python is used to generate a sequence of numbers according to the values specified by the programmer.
For example:
represents the sequence:
Notice that 5 is not included.
The range() function is commonly used when a program needs a sequence of numbers. Its use with for loops can be discussed separately later.
Syntax of range()
Python provides three forms of the range() function:
Where:
| Argument | Meaning |
|---|---|
| start | The number from which the sequence starts |
| stop | The number at which the sequence stops (not included) |
| step | The difference between consecutive numbers |
1. range(stop)
When only one value is given, it is treated as the stop value.
It represents:
So:
generates numbers starting from 0 and ending just before 5.
Therefore:
2. range(start, stop)
Two values can be specified:
Here:
- start = 2
- stop = 7
The sequence is:
Again, the stop value 7 is not included.
3. range(start, stop, step)
Three values can be specified:
Here:
- start = 2
- stop = 10
- step = 2
The sequence is:
The numbers increase by 2 each time.
Important Point
The stop value in range() is always excluded.
For example:
represents:
not:
A Small Experiment
You can use list() to see the numbers represented by a range object:
Output:
Here, range(5) creates a range object, and list() converts that sequence into a list so that we can easily see its values.
More Examples
Practice Programs: Negative step Values
The following programs demonstrate descending sequences, negative step values, and zero or negative arguments.
1. Descending sequence
Output: [5, 4, 3, 2, 1]
2. Negative step of 2
Output: [10, 8, 6, 4, 2]
3. Starting from zero
Output: [0, -1, -2, -3, -4]
4. Negative start and stop
Output: [-1, -3, -5, -7, -9]
5. Zero step — what happens?
Output: ValueError: range() arg 3 must not be zero