The Python range() Method


The python range() function creates a list of integers, typically used in the for loop.

syntax of range function

range(start, stop[,step])

Parameter description:

  • start:Count from start, default from 0
  • Stop:Count to the end of the stop, but not the stop.
  • step:step length, default is 1.

Related course: Complete Python Programming Course & Exercises

Range Example

With one parameter

The programs below demonstrate usage of range(). The sequence ends with stop-1, where the parameter is stop.

range(10)
[0,1,2,3,4,5,6,7,8,9]
range(1,11)
[1,2,3,4,5,6,7,8,9,10]
range(0,30,5)
[0,5,10,15,20,25]
range(0,-10,-1)
[0,-1,-2,-3,-4,-5,-6,-7,-8,-9]
range(0)
[]
range(1,0)
[]

range can also be used in for, looping out each letter of the word

x='python'
for i in range(len(x)):
    print(x[i])

Only one parameter, representing all integers from 0 to this parameter, excluding the parameter

ran=range(10)
#define a list, which is used to age all the numbers in the range of the range as a list
arr_str=list(ran)
print(ran)
print(arr_str)

This outputs:

>>> ran=range(10)
>>> arr_str=list(ran)
>>> print(ran)
range(0, 10)
>>> print(arr_str)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

python range method

With two parameters

Two arguments, the first for the left boundary, the second for the right boundary, and the range for all integers from the left boundary to the right boundary, left closed and right open.

ran=range(1,15)
arr_str=list(ran)
print(ran)
print(arr_str)

Outputs:

>>> ran=range(1,15)
>>> arr_str=list(ran)
>>> print(ran)
range(1, 15)
>>> print(arr_str)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

With three parameters

Three parameters, the first representing the left boundary, the second representing the right boundary, and the third representing the step step, i.e. the difference between two integers, left closed and right open.

ran=range(1,15,2)
arr_str=list(ran)
print(ran)
print(arr_str)

Outputs:

>>> ran=range(1,15,2)
>>> arr_str=list(ran)
>>> print(ran)
range(1, 15, 2)
>>> print(arr_str)
[1, 3, 5, 7, 9, 11, 13]
>>>