Home ยป Python Range Function

Python Range Function

Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given.

In case the start index is not given, the index is considered as 0, and it will increment the value by 1 till the stop index.

Syntax

range(start, stop, step)

Parameters

  • start: (optional) The start index is an integer, and if not given, the default value is 0.
  • stop: The stop index decides the value at which the range function has to stop. It is a mandatory input to range function. The last value will be always 1 less than the stop value.
  • step: (optional).The step value is the number by which the next number is range has to be incremented, by default, it is 1.

Return value:

The return value is a sequence of numbers from the given start to stop index.

Python range() has been introduced from python version 3, before that it was xrange() that was used.

Both range and xrange() are used to produce a sequence of numbers.

The range() is implemented slightly different in the Python versions:

  • Python 2.x: The range() function returns a list.
  • Python 3.x: The range() function generates a sequence.

Examples

Here are a number of examples showing the range() function

No start and step specified

This example shows how to print the values from 0-9 using range().

The value used in range is 10, so the output is 0 1 2 3 4 5 6 7 8 9

Since the start is not given the start is considered as 0 and the last value is given till 9. The last value is always 1 less than the given value i.e. stop-1.

for i in range(10):
    print(i, end =" ")

Output:

0 1 2 3 4 5 6 7 8 9

Using start and stop

In this example, the start value is 2, and stop value is 7. Here the start index is 2, so the sequence of numbers will start from 2 till the stop value.

for i in range(2,7):
    print(i, end =" ")

Output:

2 3 4 5 6

Using start, stop and step

The start value is 2, so the sequence of numbers will start at 2. The stop value is 15, so the sequence of numbers will stop at (15-1).

The step is 4, so each value in the sequence will be incremented by 4. If the step value is not given, the value for step defaults to 1.

for i in range(2, 15, 4):
    print(i, end =" ")

Output:

2 6 10 14

Decrementing the values using negative step.

The parameter step with negative value in range() can be used to get decremented values. In the example below the step value is negative so the output will be in decremented from the range value given.

for i in range(10, 0, -1):
    print(i, end =" ")

Output:

10 9 8 7 6 5 4 3 2 1

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More