In this article, We will learn what does range function do in python and how to use it. range() is a built-in function of python. The
range() function generates the integer numbers between the given start integer to the stop integer, which is generally used to iterate over with for Loop.
range() accepts an integer and returns a range object, which is nothing but a sequence of integers. Let’s understand how to use range() function with the help of simple examples.
print("range function example") print("Printing range function result") for i in range(6): print(i, end=', ')
range function example Printing range function result 0, 1, 2, 3, 4, 5,
In the output, we got integers from 0 to 5. range() function doesn’t include the last number in the result. The most common use of range() function in python is to iterate sequence type (List, string etc ) with for and while loop.
Python range() function syntax and arguments
range (start, stop[, step])
- range() takes three arguments.
- Out of the three 2 arguments are optional. I.e., Start and Step are the optional arguments.
- A start argument is a starting number of the sequence. i.e., lower limit. By default, it starts with 0 if not specified.
- A stop argument is an upper limit. i.e.generate numbers up to this number, The
range()function doesn’t include this number in the result.
- The step is a difference between each number in the result. The default value of the step is 1 if not specified.
Python range() function Examples
Let see all the possible scenarios now. Below is the three variant of range() function.
Example one – Using only one argument in range()
print("Print first 5 numbers using range function") for i in range(5): print(i, end=', ')
Print first 5 numbers using range function 0, 1, 2, 3, 4,
- Only stop argument is passed to
- So by default, it takes
start = 0and
step = 1.
Example Two – using two arguments (i.e., start and stop) in range() function
print("Print integers within given start and stop number using range() function") for i in range(5, 10): print(i, end=', ')
Print integers within given start and stop number using range() function 5, 6, 7, 8, 9,
- Only two arguments (the start and stop) are passed to the range function.
- So by default, it took step argument value as 1.
Example Three – using all three arguments in range() function
print("using start, stop, and step arguments in Python range() function") print("Printing All odd numbers between 1 and 10 using range()") for i in range(1, 10, 2): print(i, end=', ')
using start, stop, and step arguments in Python range() function Printing All odd numbers between 1 and 10 using range() 1, 3, 5, 7, 9,
All three arguments are specified. i.e.
start = 1,
stop = 10,
step = 2. Note:- In the above program step value is 2 so the difference between each number is 2.
Points to remember about python range() function arguments
- range() function only works with the integers i.e., whole numbers.
- All argument must be integers. You can not pass a string or float number or any other type in a start, stop and step argument of a range().
- All three arguments can be positive or negative.
- The step value must not be zero. If a step is zero python raises a ValueError exception.
Python range() with for loop
As you know for loop executes a block of code or statement repeatedly for the fixed number of times. Using for loop we can iterate over a sequence of numbers produced by the
Let see this with an example. Suppose we have a list of 5 numbers and you want to display each element by doubling it let see how to do it using a for loop and range() function.
print("Double the list numbers using for loop and range() function") sampleList = [3, 6, 9, 12, 15] for i in range(len(sampleList)): print( "Element Index[", i, "]", "Previous Value ", sampleList[i], "Now ", sampleList[i] * 2)
Double the list numbers using for loop and range() function Element Index[ 0 ] Previous Value 3 Now 6 Element Index[ 1 ] Previous Value 6 Now 12 Element Index[ 2 ] Previous Value 9 Now 18 Element Index[ 3 ] Previous Value 12 Now 24 Element Index[ 4 ] Previous Value 15 Now 30
- Here using a
len(list), we got total elements of a list so we can iterate for loop fixed number of time. In each iteration using a range() function loop gets the index of the current element.
- Note: variable
iis not getting the value 0, 1, 2, 3, 4 at the same time.
iget value sequentially. i.e., in the first iteration
i= 0. in the second iteration
ibecome 1 and so on.
Python range inclusive
range(n) is of exclusive nature that is why it doesn’t include the last number in the output. i.e., The given end point is never part of the generated result.
range(0, 5) = [0,1,2,3,4]. I.e. it generates integers from 0 to up to 5 but doesn’t include 5. If you want to include the last number in the output i.e., If you want an inclusive range then pass
stop argument value as
Inclusive range() example in Python.
print("Printing inclusive range") start = 1 stop = 5 step = 1 # to get inclusive range change stop as stop+step stop +=step #now stop is 6 for i in range(start, stop, step): print(i, end=', ')
Printing inclusive range 1, 2, 3, 4, 5,
Example 2: Inclusive range
print("Printing inclusive range") start = 2 stop = 10 step = 2 # to get inclusive range change stop as stop+step stop +=step #now stop is 12 for i in range(start, stop, step): print(i, end=', ')
Printing inclusive range 2, 4, 6, 8, 10,
Python range Step
A step is an optional argument in the range function. The step is a difference between each number in the sequence. The default size of a step is 1 if not specified. If the step size is 2, then the difference between each number is 2.
We can perform lots of operations by effectively using step argument such as reversing a sequence, printing negative ranges.
Decrementing with range using negative step
We can use negative values in all the arguments of range() function i.e., start, stop and step. Let us see how.
start = -2 stop = -10 step = -2 print("Negative number range") for number in range(start, stop, step): print(number, end=', ')
Negative number range -2, -4, -6, -8,
Let’s understand above program:
start = -2
stop = -10,
step = -2.
in the 1st iteration of for loop = [-2]. in the 2nd iteration of for loop = [-2,-4] because -2+(-2) == -4 and so on and Last iteration output is [-2,-4,-6,-8]
Decrementing with the range from Negative to Positive number
Here in this example, we can learn how to use step argument to display a range of numbers from negative to positive.
print ("printing range from negative to positive") for num in range(-2,5,1): print(num, end=", ")
The output of the above program
printing range from negative to positive -2, -1, 0, 1, 2, 3, 4,
Python range from Positive to Negative number
Here in this example, we can learn how to use step argument effectively to display numbers from positive to negative.
print (" printing range from Positive to Negative") for num in range(2,-5,-1): print(num, end=", ")
printing range from Positive to Negative 2, 1, 0, -1, -2, -3, -4,
Convert Python range() to List
Python 3’s range uses the generator. Python 3’s range() will produce value when for loop iteration asked for it. i.e., it The
range() doesn’t produce all numbers at once.
Python range() function returns an immutable sequence object of integers, so its possible to convert range() output to python list. Use list class to convert range output to list. Let’s understand this with the following example.
print("Converting python range() to list") even_list = list( range(2,10,2)) print("printing list", even_list)
Converting python range() to list printing list [2, 4, 6, 8]
Using float Numbers in Python range()
Python range() function doesn’t support the float numbers. i.e., we cannot use floating-point or non-integer number in any of its argument. we can use only integer numbers.
However, we can create a custom range function where we can use float numbers like 0.1 or 1.6 in any of its argument. I have demonstrated this in the below example.
def frange(start, stop=None, step=None): if stop == None: stop = start + 0.0 start = 0.0 if step == None: step = 1.0 while True: if step > 0 and start >= stop: break elif step < 0 and start <= stop: break yield ("%g" % start) # return float number start = start + step print ("Printing float range") floatList = frange(0.5, 1.0, 0.1) for num in floatList: print (num)
Printing float range 0.5 0.6 0.7 0.8 0.9
Reverse range in python
If you want to print sequence of numbers within range by descending order or reverse order then its possible, there are two ways to do this.
First is to use a negative or down step value. i.e., set the third argument of a
For example, if you want to display a number sequence like [5,4,3,2,1]. Use negative step value. The following code shows the same.
print ("Displaying list of numbers by reverse order using range()") for number in range(4,-1,-1): print (number, end=', ')
Displaying list of numbers by reverse order using range() 4, 3, 2, 1, 0
Alternatively, use the reversed function.
reversed function used to reverse a list of any type. To use the
reversed function you need to convert a range output to list first. Let see this with an example.
print ("Printing reversed range") reverseed_range = list(reversed(range(0,5))) print(reverseed_range)
Printing reversed range [4, 3, 2, 1, 0]
Python’s range() vs xrange() Functions
range() function works differently between Python 3 and Python 2.
Working of range and xrange in Python 2
- Both the range() and xrange() function generates the sequence of numbers. but
range()produce a list, and
xrange()produces an xrange object i.e. a sequence object of type xrange.
- range() generates all numbers at once.
- xrange() doesn’t generate all numbers at once. it produces number one by one as for loop moves to the next number
We can test the type of these functions In Python 2 with the following examples: –
print type(range(10)) Output = type 'list'.
print( type( xrange(10) ) ) output = class 'xrange'
print( type( range(10) ) ) output = class 'range'
Should we always favor range() over xrange()?
If you are using python 2.x then yes. as you know in python 2.x range() function loads all the numbers in the main memory before iterating them by for loop this leads to high memory usage and increased execution speed.
If you want to write code that will run on both Python 2 and Python 3, you should use range().
Python range() over character or alphabet
Is there a way print range of characters or alphabets? For example like this.
for char in range ('a','z'): print (char)
Note: Above code is a pseudo-code.
Yes, It’s possible using the custom generator. let’s see the example. in the following example, I have demonstrated how to generate ‘a’ to ‘z’ alphabet using the custom range() function. this is inclusive, means it also includes the last character.
Here we used a ASCII value range and then convert an ASCII value to a letter using a
Python Program to Generate letters from ‘a’ to ‘z’ using custom range() function
print ("""Generates the characters from `a` to `z`, inclusive.""") def character_range(char1, char2): for char in range(ord(char1), ord(char2)+1): yield (char) for letter in character_range('a', 'z'): print( chr(letter), end=", " )
Generates the characters from `a` to `z`, inclusive. a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,
How does the Python range() function work?
Python range() return value is determined by formula and some value constraints.
range[n] = start + step * n ( for both positive and negative step value ) For Positive step value n >=0 and range[n] < stop For Negative step value n >= 0 and range[n] > stop
Note: If a step is a non-zero, Python range() function checks the value constraint. range() returns an Empty sequence If it doesn’t meet the value constraint.
So you must be thinking why does python range(start, end) not include end ? it has a very simple answer because index always starts with ZERO in python. if you count total numbers between range (5) you will get [0,1,2,3,4] i.e. total count is 5.
Concatenating the result of two range() function in python
Let say you want to add
range(5) + range(10,15). (Note: this code is a pseudo-code.) And you want the concatenated range like
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14].
Can we concatenate the output of two range functions?
Yes, this is possible using itertools. using chain() function of itertools we can do this.
Program: Concatenating two range function results.
from itertools import chain print ("Concatinated two range() function") concatenated_range = chain(range(10), range(50, 75)) for num in concatenated_range: print(num,end=", ")
Concatinated two range() function 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
Access Python range() result with its index value
range() is constructor returns a range object which is nothing but a sequence of numbers, this range object can also be accessed by its index using slice notation. It supports both positive and negative indices. below example explains the same.
print("accessing python range objet with its index") first_number = range(0,10) #printing 0th position number i.e. index ZERO means first number print("First number in given range is: ", first_number) fifth_number = range(0,10) print("fifth number in given range is: ", fifth_number)
accessing python range objet with its index First number in given range is: 0 fifth number in given range is: 4
you can also convert python range() output to list and access this list with its index like this.
sample_list = list( range(1,10) ) print ("second element is ", sample_list )
second element is 2
To practice what you learned in this article, I have created a Python Basic Quiz and Exercise.
Let me know your comments and feedback in the section below.