Python range() Function

Generates a sequence of numbers within a given range

Usage

The range() function generates a sequence of numbers from start up to stop, and increments by step.

When used in a for loop, range() provides a simple way to repeat an action a specific number of times.

for x in range(3):
    print('Hello!')
# Prints Hello! Hello! Hello!

Syntax

range(start,stop,step)

Python range() function parameters
ParameterConditionDescription
startOptionalA number specifying start position.
Default is 0.
stopRequiredA number specifying end position.
stepOptionalA number specifying the increment.
Default is 1.

range(stop)

When you call range() with just one argument, you will get a sequence of numbers starting from 0 up to the specified number.

# Generate a sequence of numbers from 0 to 6
for x in range(7):
    print(x)
# Prints 0 1 2 3 4 5 6

Note that range(7) is not the values of 0 to 7, but the values 0 to 6.

range(start, stop)

The range starts from 0 by default. However, you can start the range at another number by adding a start parameter.

# Generate a sequence of numbers from 2 to 6
for x in range(2, 7):
    print(x)
# Prints 2 3 4 5 6

You can generate a range of negative numbers as well.

for x in range(-5,0):
    print(x)
# Prints -5 -4 -3 -2 -1

range(start, stop, step)

The range increments by 1 by default. However, you can specify a different increment by adding a step parameter.

# Increment the range() with 2
for x in range(2, 7, 2):
    print(x)
# Prints 2 4 6

You can go through the numbers in reverse order (decrementing) by specifying a negative step.

# Reverse Range
for x in range(6, 1, -1):
    print(x)
# Prints 6 5 4 3 2

List from the Range

You can construct a list of numbers from the range using list() constructor.

L = list(range(7))
print(L)
# Prints [0, 1, 2, 3, 4, 5, 6]

Range for Float Numbers

The range() function works only with integers. It doesn’t support the float type. So, you can use arange() function from NumPy module to generate the range for float numbers.

import numpy

for i in numpy.arange(0, 3, 0.5):
    print(i)
# Prints 0.0 0.5 1.0 1.5 2.0 2.5

Indexing & Slicing

You can access items in a range() by index or even slice it, just as you would with a list.

# indexing
print(range(7)[3])
# Prints 3

# slicing
print(list(range(7)[2:5]))
# Prints [2, 3, 4]