Ways to use Python range with 4 examples

The Range function of Python

Python has a function called range() that is used to create a list of integers. For example, 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.

The Range of Python is mostly used in the for loop. See examples below.

Syntax of range

Following is the general syntax of Python range function:

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

Simple range()

Range(5)

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:

Range(10,15)

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 Python range. We will create a range and assign it to a variable and then display it by using the Python print function.

Output will be:

range(0, 5)

Using range in for loop

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

Output will be:

0

1

2

3

4

You can see, we simply used the range function in the for loop, range(5). After that, a print function is used to display the values of 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 print the range numbers.

Output will be:

10

11

12

13

14

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 in Python with specified steps example

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

The output will be:

0

5

10

15

20

25

30

35

40

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.

Also see – Python while loop | xrange

Was this article helpful?

Related Articles

Leave A Comment?