In this article, you’ll learn how to explain the range function in Python. Before we get started, if you want to conditional statements in python, please go through the following article: Define Functions in Python.

One of Python’s built-in immutable sequence types is range(). This function is extensively used in loops to control the number of types of loops that have to run. In simple words range is used to generate a sequence between the given values.

The range() function can take 1 to 3 of the following arguments:

  • Start: The integer value for the origin of the sequence, if not passed implicitly it’s 0
  • Stop:  The integer value up to which the sequence will get generated but won’t include this number. This is a required argument that must be passed,
  • Step: Establishes the difference between each iteration it can be positive or negative if not given the default step is 1

The order of arguments is as follows, range(start, stop, step). Note that all parameters must be integers however they can be positive or negative.

Using Range Function In Python

Let’s start with generating a simple series and printing it out

Above for loop will print every number from 0 to 5 maintaining a constant difference 1. Output:

It’s worth mentioning that similar to list indexing in range starts from 0 which means range(j) will print the sequence till (j-1) hence the output doesn’t include 6. As mentioned earlier the default value of start is 0 and for step, it’s 1, therefore the below code produces the same output.

Output:

Generating a decreasing sequence is also possible by specifying a negative value to step argument.

Output:

The range function can also be used to iterate over the elements of a list.

Output:

It’s worth noting that in Python 2 the output of the range function was a list but in python 3 the range() function doesn’t produce a list so we can’t perform list operation on it, but converting the output to a list is possible using the built-in list() method.

Python’s Range Function Explained

The article was published on October 3, 2020 @ 4:11 PM

Leave a Comment