ExampleEdit & Run

Use the range() function

r = range(10, 20)

for i in r:
   print(i)
copy
Output:
10 11 12 13 14 15 16 17 18 19 [Finished in 0.010480676777660847s]

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.

Syntax:
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.
Parameters:

The function returns a range object with values starting from the start to the stop(itself not included) with step as the interval.

ExampleEdit & Run

generate a sequence of integers from 0 to  10 

for i in range(10):
   print(i)
copy
Output:
0 1 2 3 4 5 6 7 8 9 [Finished in 0.010117508471012115s]

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.

ExampleEdit & Run

With start and step given

for i in range(10, 60, 5):
   print(i)
copy
Output:
10 15 20 25 30 35 40 45 50 55 [Finished in 0.00994713045656681s]

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.

ExampleEdit & Run

A decreasing range

for i in range(10, 0, -1):
    print(i)
copy
Output:
10 9 8 7 6 5 4 3 2 1 [Finished in 0.009995928034186363s]

In the above example, the range starts at 10 and moves down to 0  with -1 as the interval between the  values.

ExampleEdit & Run
for i in range(50, 0, -5):
    print(i)
copy
Output:
50 45 40 35 30 25 20 15 10 5 [Finished in 0.010250980965793133s]

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.

ExampleEdit & Run

Cast  a range object in to a list

r = range(0, 20, 2)

print(list(r))
copy
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] [Finished in 0.010124212130904198s]
ExampleEdit & Run

Cast a range object into a tuple

r = range(0, 50, 5)

print(tuple(r))
copy
Output:
(0, 5, 10, 15, 20, 25, 30, 35, 40, 45) [Finished in 0.009989115409553051s]
ExampleEdit & Run

Cast a range into a set

r = range(50, 0, -5)

print(set(r))
copy
Output:
{35, 5, 40, 10, 45, 15, 50, 20, 25, 30} [Finished in 0.009963810443878174s]