The Range function of Python

Python has a function called range() that is used to create a list of integers. For example, a range(5) has the length of 5 numbers. By default, Python range starts from 0.

However, this can be specified where the range should start and end. For instance, range between 10-15 will be the sequence of 5 numbers starting from 10 and ending at 14.

See an example of Range

The range function is mostly used in the for loop. See examples below.

How to use the range function

Following is the general syntax of Python range function:

range([start], stop, [step])

Simple range()


The above range will start from 0.

How to specify start and end of range

This is how you can specify the start and end of the range in Python:


Note, if the step argument is not given (which is optional) the default step would be 1.

A simple range example

Following is an example of range Python function where we will create a range and assign it to a variable and then display it by using the print function.

See this example online

The output:

range(0, 5)

Using range in for loop

Following example shows how to use Python for loop with the range function.

See this example online

The Output:






You can see, we simply used the range function in the for loop i.e. range(5). After that, a print function is used to display the values of the variable i, which is equal to the current value in the range and moves ahead with each iteration. Also, note that it started from 0.

Range with specified start and end example

The example below starts the range from 10 and ends at 15. The for loop is used to display the range numbers.

See this example online

The output:






The only difference between the above and this example is we specified the start and end position of the range. The first number, which is 10, tells to start the range from number 10.

Range with specified steps example

Python Range function also allows specifying the steps or intervals between first to end numbers. For example range from 1 – 45 with the gap of 5. See example below:

See this example online

The output will be:










In this example, we specified the third parameter, which is the gap between each number. The print function displayed the range numbers with a gap of five from 0 to 45.


Further reading: Python while loop