Use the range() function
r = range(10, 20)
for i in r:
print(i)
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) .
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.
generate a sequence of integers from 0 to 10
for i in range(10):
print(i)
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.
With start and step given
for i in range(10, 60, 5):
print(i)
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.
A decreasing range
for i in range(10, 0, -1):
print(i)
In the above example, the range starts at 10 and moves down to 0 with -1 as the interval between the values.
for i in range(50, 0, -5):
print(i)
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.
Cast a range object in to a list
r = range(0, 20, 2)
print(list(r))
Cast a range object into a tuple
r = range(0, 50, 5)
print(tuple(r))
Cast a range into a set
r = range(50, 0, -5)
print(set(r))