Python Range Function

By | January 4, 2019

Let us learn what is Python range function and how to implement the range() function in multiple ways with examples, explanation and much more.

What is Python Range Function?

In simplest words, the range() function generates a series of integers between a start point and an end point. It accepts 3 parameters to process the data.

An important point to note is that the range() function works only with Integers. It does not accept float values. Let’s look at the syntax.

Syntax

`range(START, STOP, STEP)`
• START: This parameter indicates the starting point or the lower limit. This is an optional parameter. Therefore, if the start parameter is blank, it defaults to 0.
• STOP: This parameter indicates the endpoint for the series of integers to be generated, also known as the upper limit. This is a mandatory parameter.
• STEP: This parameter indicates the increment or difference between the 2 adjacent numbers within the sequence of integers. Since, this is an optional parameter, if it’s empty, it defaults to 1. This parameter cannot be zero.

Important Pointers:

• All the parameters (Start, Stop, Step) can be either positive or negative.
• The range() function accepts only integer values; float values will throw an error.
• The Start is a mandatory parameter; Step and Stop are optional input parameters.
• The range() function works a little differently in Python 2.x and Python 3.x versions.
• The value for Step parameter can never be 0. If it is 0, then it will raise a ValueError exception.

Let us now look at the different examples of how the range() function can be implemented in Python.

Note: This Python program is compiled with Python 3.7.2 Shell on Microsoft Windows OS.

Example 1

```>>>
>>> a = range(1, 10, 2)
>>> list(a)
[1, 3, 5, 7, 9]
>>>```

The range is printed using the list() function here. The print function does not work in this case.

Example 2

```>>>
>> a = range(10)
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>```

The only input to the range() in this example if the stop or the endpoint of the series. The default Start point is 0 and the default increment is 1.

Example 3

```>>
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]
>>>```

In this example, we’re directly calling the range() function inside the list() function with all the parameters.

Example 4

```>>>
>>> a = range(20, 1, -2)
>>> list(a)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
>>>```

This is an example for reversing the range(). Here’s we’re using a negative integer as the increment. The start point is 20, and therefore, it decrements from 20 until 1.

If you have any doubts about Python range function, let us know about it in the comment section.