The Python Range Function (How To: With Examples)
The python range function is a block of code that generates an immutable sequence of numbers. Range() is a built-in function and has three parameters. These are the (1) start, (2) stop, and (3) step parameters.
- Start: the first parameter is used to define the starting point of a sequence. By default, the start number is zero.
- Stop: the second parameter defines the stopping point of the sequence. It is mandatory to specify this parameter for the code to run properly.
- Step: the third parameter is the step size. It specifies the size of the increment for each iteration. It is also optional and has a default value of one.
The main purpose of the range() function is generate a list of numbers. The range() function will begin at the start value, and then increment this using the step size to produce additional values for the list. The stop value tells Python when to terminate the list.
The range() function can be used to make a variety of number lists. They could be odd or even numbers, positive or negative. The list can also be ascending or descending by using a positive or negative step size, respectively.
Developers often use the range function to write loops without lists or tuples. You can use it to iterate over any iterable object or call it when you need to perform an action in ‘N’ number of times. It uses the same memory space for any size or range it represents. As a result, it works fast and is very efficient.
In this blog post, we will expose how the python range function works, and how to use it to get and manipulate sequences. We also show you how to save the elements you can get from reiterating the python range to a list for other uses.
What is the Python Range Function?
The range() function is a built-in function that is used to make a list of integers.
The use of the range function differs in python 2 and python 3. The range() and xrange() functions are what python 2 uses to produce a sequence of numbers. Python 3, however, removed the original range() function and renamed the xrange() function as range(). Since python 3 is the latest version, not many developers still use python 2.
The range() function generates numbers based on the information stored in memory. The memory holds the start, stop and step values and uses them to calculate individual items and subrange. It is only through using the loop iteration that you instruct the program to generate the values one after the other for printing or further use.
To understand how the range() function works, let’s take a look at the first few values it would produce.
The first value in the sequence is the start value. The second number in the sequence will be the start value plus the step value. The third number will be the second plus the step value. This continues until the last number. The last number is always lower than the stop value.
first value = start value
second value = start value + step value
third value = second value + step value
fourth value = third value + step value
stop/break when the nth value exceeds the stop value
#The following example shows the basic operation of the range() function:
range(0, 5, 2)
In the above example, the first value in the sequence is zero (0), the start value. The step size (2) is then added to the first value to produce the second value, 2. This happens again for the third value in the sequence, i.e. 2 + 2 = 4. Python then sees that another step would be beyond the end value specified; the next number in the sequence would be six (6), but this is greater than the end value specified (5). The final value must always be less than the end value, so the sequence is terminated.
The step value should never be zero. Inputting zero as your step value would give you an error message which will mention that the argument (step value) must not be zero.
Python Range Function For Loop
A for loop in python repeatedly executes a function or statement for a fixed amount of time. Reiteration over a sequence of numbers generated by the range() function works best with the for loop.
The range() function can be used inside a for loop:
Range Function With One Argument: The Simplest Case
With a single argument, the range() function will assume a default start value of zero (0) and a default step size of one (1):
for i in range(5):
#output is 0, 1, 2, 3, 4 on consecutive lines.
Range Function With Two Arguments: Specifying a Start Value
Adding a second argument allows us to specify a start value. In the following code, we are using a start value of one (1):
for i in range(1, 5):
#output is 1, 2, 3, 4. It starts from 1 since the input for the start value is 1.
Range Function With Three Arguments: Specifying Start, Stop, and Step Values
In this example, we are using the range function with three arguments. This allows us to choose the starting value of the sequence, to specify the upper limit of the sequence, and also produce a sequence with a custom step size.
#specific start, stop and step values
for i in range(0, 5, 2):
print(“The current number i displays is: “, i)
The current number i displays is: 0
The current number i displays is: 2
The current number i displays is: 4”’
One thing to note is that the range function works only with integer arguments. Integers can be positive or negative. Other data types such as floats, characters and Boolean will not fit into the range function.
Range Step Size
A step determines the consecutive difference between the numbers in the result sequence. If you do not specify this value, the program will assign the step value as one.
You can use step arguments to reverse a sequence such as a list. Just as positive step values indicate an increment, negative step values will cause a decrement in the sequence. Also, the step argument is very useful for generating multiples of a number in a given range.
# using step argument to print decreasing range sequence
for i in range(st, sp, -stp):
print(i, end=” “)
#where st, sp and -stp are start, stop and negative step values respectively.
#the end=” ” indicates that the last character is to end with whitespace instead of a new line
for i in range(0, 10, -2):
print(i, end=” “)
Output is 10, 8, 6, 4, 2
Using step argument to print multiples of a number in an increasing order:
for i in range(5, 50, 5):
print(i, end=” “)
Output is 5, 10, 15, 20, 25, 30, 35, 40, 45
Range Function With Negative Step Size
Any of the arguments given to the range() function can be negative. Negative start and stop values of a range can be negative, as well as the step size. Giving the range() function a negative step size means tells Python to produce a list with numbers in descending/decreasing order. The negative sign affects the numbers in the sequence in an opposite manner when compared to an all-positive range function.
Printing and iteration of all negative numbers mostly utilize a negative range function. See sample code below:
range(-st, -sp, -stp)
#where -st, -sp and -stp are the negative start, stop and step values respectively
#Example: printing of a sequence of negative numbers
for i in range(-1, -6, -1):
print(i, end=” “)
Output is -1, -2, -3, -4, -5
You can also get the negative reverse range of a sequence using a positive step integer and a negative stop value. Since the stop value is negative, the step value can be zero.
Example (1): Printing of a negative reverse range
for i in range(-5, 0):
Output is: -5, -4, -3, -2, -1
for i in range (-5, 5):
Output is: -5, -4, -3, -2, -1, 0, 1, 2, 3, 4
There is no limit to the length of positive and negative numbers in a sequence that the range function can generate.
for i in range(3, -4, -1):
Output is 3, 2, 1, 0, -1, -2, -3
If your interest lies in getting a sequence of multiples of a negative number, your start value should be zero or the negative number itself.
Example 4: printing of negative multiplies
for i in range(0, -50, -7):
print(i, end=” “)
Output is 0, -7, -14, -21, -28, -35, -42, -49
Python range () reverse
We have covered a bit of the reverse range above where you use your knowledge of the right placement of start, stop, and step values to get a sequence in decreasing order which is synonymous with a reversed one.
However, python does give a reverse function which can be used inside the range function. The reverse function makes it easy for the program to loop over the series in a reversed order.
To reverse manually with range(), you have to follow these four simple rules:
- The start value must be the maximum number among the three.
- The stop value should be the minimum number
- The step value should decrement by a negative value.
- If the sequence you’re working with has all negative numbers, the first two rules have to be reversed. See the examples below.
for i in range(10, 1, -2):
Output is 10, 8, 6, 4, 2
for i in range(1, -10, -2):
Output is 1, -1, -3, -5, -7, -9
Using the reverse function with range() eliminates possible mistakes due to a wrong calculation of start, stop and step values. It is easier to use and gives the same result as correctly reversing manually using range().
The format for using the range() within a reverse() is given below:
#where stp is the stop value
for i in reversed(range(4)):
Output is 4, 3, 2, 1, 0
for i in reversed(range(-4)):
Output is -4, -3, -2, -1, 0
Python Range Inclusive
As with all other examples above (except for the reversed range function), the range function does not print the stop value by default. The last output is usually the stop value minus the step value.
An inclusive range is a range that includes the stop value in its output. To do this, you have to add the step value to the stop value. Hence, the stop value in the code has to change for the actual stop value you need to join the output.
Example: You want the beginning of a sequence of multiples of 4 to be 4 and the end to be 16 using 4 as the start value and 16 as the stop value will not give you 16 as the last value:
for i in range(4, 16, 4):
Output is 4, 8, 12
#To include 16 in the output, add the step value (4) to the stop value (16).
for i in range(4, 20, 4):
Output is 4, 8, 12, 16
Python Range To List
The python range() does not commit the elements it generates to memory. The range object only returns them during a reiteration. In contrast, a list stores the elements to memory.
The range function saves memory space while working with lists is faster. If you need to convert a range object to a list, here are two easy ways to do that: (1) Use a for loop, and (2) Use the list() function.
Python Range to List Using For Loop
Since the for loop iterates over each element in a range, you can simply append these elements (as they are reiterated) to a list. See sample code below:
range_obj = range(4, 20, 4)
list_one = list()
for x in range_obj:
Output is [4, 8, 12, 16]
Python Range to List Using List Function
You can create a range object and convert it directly to a list using the list function. See sample code below:
range_one = range(5, 40, 5)
list_one = list(range_one)
Output is [5, 10, 15, 20, 25, 30, 35]
Conclusion – The Python Range() Function
Python’s built-in range function is straightforward to use. It takes three arguments and outputs a sequence of values. To use range(), we provide Python with a range of numbers and a step size. The arguments can have positive values or negative. A positive number as a step size indicates an ascending step, while a negative number indicates a descending step.
The importance of the range() function lies in its quick generation of a series of numbers within a specific range without taking up memory. Moreover, these elements can be converted into a list when necessary without any complexity. And unlike lists where you have to specify each member yourself, the python range function eliminates this work giving you a less crowded code and more time.
In this Python tutorial, we’ve covered the range() function and many of its’ options and use-cases.