Python range() is a built-in function that returns or generates an immutable sequence of numbers, starting from the lower bound to the upper bound.

python range() function

Python range() Syntax

Depending on the set of parameters Python range() has two forms.

range(stop)
  • stop (required) – the number of integers to be returned starring from 0
range(start,stop[,step])
  • start (required) – an integer specifying the start value for the range or sequence to be generated
  • stop (required) – boundary value up to which (excluding this value) the range or sequence is to be returned
  • step (optional) – the step size, the difference between each number in the sequence
    • The default value of step is 1, if not explicitly provided
    • If the step value is non-zero, then the corresponding sequence is returned by grading each element by the step value
    • If stepsize is 0, then ValueError is raised

Python range() function in Python 2.7 and 3.x

  • Python 2.7: range() returns list in Python 2.7
  • Python 3.x: range() returns a range or sequence in Python 3.x

Python range() Example

>>> range(0)
range(0, 0)

>>> list(range(5))
[0, 1, 2, 3, 4]

>>> list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> #including step size
>>> list(range(1,15,3))
[1, 4, 7, 10, 13]

>>> #using 0 step size
>>> range(1,5,0)
Traceback (most recent call last):
 File "<pyshell#8>", line 1, in <module>
 range(1,5,0)
ValueError: range() arg 3 must not be zero

As you can see, range() in Python 3.x returns range or sequence and converting to list will show the list of range.

And also range() raises ValueError when 0 is supplied as step size.

Python range() with Negative step value

>>> list(range(1,-15,-3))
[1, -2, -5, -8, -11, -14]

Python range() and For loop

>>> #for loop with single parameter
>>> for i in range(4):
        print(i)
0
1
2
3

>>> #for loop with step size
>>> for i in range(1,9,2):
        print(i)
1
3
5
7