The range()
generates integers within a specified range. It is commonly used with loops especially the for
loop to iterate over a sequence of numbers.
range(stop) range(start, stop, step = 1) .
copy
stop | A required integer specifying the endpoint for the range. |
start | An optional integer specifying the starting value for the range. It defaults to zero. |
step | An optional integer specifying the increment value. It defaults to 1. |
The function returns a range object with values starting from the start to the stop
(itself not included) with step
as the interval.
In the above example, the range we only specified the stop
value as 10, the default values are used for the start
and step
i.e 0 and 1 respectively.
Decreasing ranges
If start
value is greater than stop
value and the step
value is negative, the range will start at a higher value then decrease as per the interval.
In the above example, the range starts at 10 and moves down to 0 with -1 as the interval between the values.
Converting range objects into other data types
Since ranges are iterable, it is possible to cast them int other iterable data types such as lists, tuples, sets, e.t.c.