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!')
# 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.

Example: Generate a sequence of numbers from 0 to 6

for x in range(7):
    print(x)
# 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.

Example: Generate a sequence of numbers from 2 to 6

for x in range(2, 7):
    print(x)
# 2 3 4 5 6

You can generate a range of negative numbers as well.

Example: Generate a range of negative numbers

for x in range(-5,0):
    print(x)
# -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.

Example: Increment the range() with 2

for x in range(2, 7, 2):
    print(x)
# 2 4 6

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

Example: Reverse Range

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

List from the Range

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

Example: Construct a list from the range

L = list(range(7))
print(L)	# [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.

You can use arange() function from NumPy module to generate the range for float numbers.

Example: Create a range for float numbers

import numpy

for i in numpy.arange(0, 3, 0.5):
    print(i)
# 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.

Example:

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

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