Python range function Examples

Python range function is built-in function which is used to generate integers. Python range function used most often to generate indexes in a for loop.

Python range Syntax:

Python range function syntax

Where:
start: The value of the start parameter
stop: The value of the stop parameter
step: The value of the step parameter.If the parameter was not supplied, then step parameter is 1.

Python range function explained:

With one parameter, range function generates a list of integers from zero to but no including the parameters value.
If we pass in two parameters, the first is taken as the lower bound.
The third(option) parameter can give a step. Python adds the step to each successive integer in the result(the default step value is 1).

Python range function Examples:

Example1: With single parameter.

L=list(range(10)) print(L)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range function starts from 0(lower bound) to 9(upper bound and not including 9) and here step will be on as default step value is 1.

for i in range(5): if i%2: print(i,"Python") else: print(i,"r2schools")

Ouput:

0 r2schools 1 Python 2 r2schools 3 Python 4 r2schools

Example2: With two parameters

L1=list(range(0,8)) L2=list(range(1,8)) print(L1) print(L2)

Output:

[0, 1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7]

Example3:Python range function with step parameter.

L3=list(range(0,10,2)) print(L3)

Output:

[0, 2, 4, 6, 8]

Here the range() function is called with a step argument of 2, so it will return every third element from 1 to 10 (off course not including 10).