is an in-built Python function, it can generate a sequence of immutable integer numbers from the given start point up to the given endpoint number. It returns an iterable
object that can iterate using a for loop statement. With
function, we can create a loop structure that can execute a code statement repeatedly up to a certain number of times. Let's see a minimal example of a
loop statement &
function, and print an integer sequence between 0 to 10.
#sequence [0,10) for i in range(10): print(i) #Output 0 1 2 3 4 5 6 7 8 9
Note: The range function only generate an integer sequence upto the end number, which means it does not include the end number. In the above example you can also notice that it only generate a sequence from 0 to 9, and exclude 10.
How to use range() function
There are two syntaxes to implement a range function in a program
range Function Syntax 1
In this syntax, the range function accepts only one argument which is mandatory. The
argument must be an integer number that represents the end number of the sequence that starts from
It returns an iterable range object, which will be a sequence of integer numbers from
. We can check the return type of range() function using the built-in
type(range(10)) # <class 'range'>
range(end) function Examples
Let's see some examples of the range() function with a single argument value.
If we pass a positive integer number to the
function, then it will create a sequence from 0 up to a specified positive integer number.
for i in range(5): print(i) #Output 0 1 2 3 4
If we pass a negative number to the single range function argument, then it will not create any sequence.
for i in range(-5): print(i) #output #nothing will be printed
range Function Syntax 2
In this syntax, we can pass three arguments to the range function.
start: It is the integer number defining the included start point of the sequence.
end: It is also the integer number argument, but it defines the excluded ending number of the sequence.
step: It is the optional argument value whose default value is 1. It defines the number of interval gaps between consecutive numbers of the sequence.
When we pass two arguments to the range function, it creates an integer sequence starting from the
number and ends at
#sequence of numbers #from 10 to 19 for i in range(10, 20): print(i, end=",")
In this example, we only specified the
arguments value to the
function. As the
argument was optional. The range function treats its value as 1, resulting in the 1 step interval gap between two adjacent numbers.
range(start, end, step)
Now let's also use the last
argument and see how it can be helpful in code. When we pass all three arguments to the
function start, end, and steps, it generates a sequence of integer numbers from the start upto end-1 with the step number of the gap between two adjacent numbers.
Let's say you want to print all the even numbers between 10 to 40. There, all you need to do is create a range function from 10 to 40 with a step of 2.
#even numbers between 20 to 40 for i in range(20, 40, 2): print(i, end =",")
In this example, you can see that the
function created a sequence from
, and the difference between the consecutive number was
that specified as the step argument. The advantage of using the third
argument is we can also create a sequence in negative integer numbers or in reverse order.
#sequence in negetive for i in range(-1, -10, -1): print(i, end =",") # -1,-2,-3,-4,-5,-6,-7,-8,-9, #sequence in reverse order for i in range(10, 1, -1): print(i, end =",") # 10,9,8,7,6,5,4,3,2,
argument must not be
otherwise, it will return the
ValueError: range() arg 3 must not be zero
Note: All the start, end and step arguments need to be integer. If any of the argument is string, float or any other data type, it will return the TypeError with following error.
- TypeError: ‘str’ object cannot be interpreted as an integer
- TypeError: ‘float’ object cannot be interpreted as an integer
- TypeError: ‘list’ object cannot be interpreted as an integer
for loop with range()
loop is an iterator that can iterate over an iterable object upto a fixed number of time. With the help of for loop, we can iterate over the sequence of numbers generated by the range() function.
How does range function work with for loop?
The range() function does not create all the sequence numbers at once. More than a Python function, it acts like a Python Generator that yields the sequence numbers one by one. The range object return by the range function does not contain all the numbers of the sequence. Instead, it only contains the start, end, and step values. This helps in saving memory space when the range values are very high.
x = range(1, 1000, 2) print(x) #range(1, 1000, 2)
The range function only generates the sequence numbers when it is required or when the for loop iterates over it. The range function does not create all the sequence numbers at once, making the object size small in the memory and loading it fast.
for i in range(start, end, [step]): #for loop body
print("Multiples of 3") for i in range(3, 31, 3): print(i, end =",")
Multiples of 3 3,6,9,12,15,18,21,24,27,30,
Iterate a list using range function and for loop
Although objects like a list, string, and tuple, are iterable objects, the
loop can directly iterate over them one item at each iteration. But these objects also support indexing, which means we can access their items or characters using index values. When we iterate over a list using for loop, we iterate over list items. There, we do not have access to its index value.
Let's say you want to make some changes in the list item based on some condition inside the for a loop. In such cases, we take the help of
function and iterate over the list with index numbers.
The advantage of using
to iterate over a list is, that we can change the value of the item using its index number and get the item position in the list. When we use the range() function to iterate over a list object, we need the length of the list object that can be found using
function. Let's discuss it with a Python program.
Suppose say we have a list
, and we need to give a
discount on those prices which are larger than 2999 rupees.
#list prices = [129, 5372, 983, 636, 384, 7732, 3000, 999] print("Old Prices:") print(prices) for i in range(len(prices)): #10% off on product with > 2999 if prices[i]>2999: prices[i] = prices[i] - (10/100)*prices[i] print("New Prices:") print(prices)
With the help of
argument, we can also create a sequence of integers in descending and reverse order.
How to Create reverse order sequence using the range function
There are two ways we can use to create a sequence of reverse numbers with a range function.
- using the negative steps.
- using the reversed function with range function
1. Using Negative Steps
Using the negative step value is a more native approach to generating a reverse integer sequence using the range function. While using the negative
argument, we need to make sure that the
argument value must be greater than the
Let's create a reverse sequence of numbers using the range function and negative step number.
#reverse sequence from 10 to 1 using range function for i in range(10, 0, -1): print(i, end =" ")
10 9 8 7 6 5 4 3 2 1
2. Using reversed Function
The reversed() is a built-in function that can
reverse a list
and tuple elements in reverse order. We can also use this function to reverse a range object, which is returned by the range function. It also returns an iterable object
that can be iterated using a
type(reversed(range(1,10))) # <range_iterator object at 0x0000016217500110>
Example 1 reverse a range function sequence from 10 to 1
#reverse the range function sequence using reversed function for i in reversed(range(1, 10)): print(i, end= " ")
9 8 7 6 5 4 3 2 1
Example 2 reverse a range function sequence from 20 to 1 with 2 step
#reverse the range function sequence using reversed function for i in reversed(range(1, 20, 2)): print(i, end= " ")
19 17 15 13 11 9 7 5 3 1
Reverse a list using the range function
In the above section, we saw how can we use the range() function to loop through a Python list from left to right. Now let's discuss how we can use the range() function to traverse back a list. When it comes to traversing a list of items using
function, we always use the
function for the index number of the list. And to access a list in reverse order, we need to create a range function that will give us the index value from
, with a step value of -1.
prices = [100, 200, 300, 400, 500, 600, 700] #start point will be the last value of list index start = len(prices)-1 #end will be -1 because we want to include 0 end = -1 #step will be -1 because we want to a sequence in reverse order step = -1 for i in range(start, end, step): print(prices[i], end =" ")
700 600 500 400 300 200 100
Create a list using the range function
As we know that that range function returns a sequence of integer numbers as a range object. The returned range object can be converted into a Python list using the
function. With the range and list functions, we can initialize a new list with a fixed size.
Let's say we want to initialize a list that contains 100 items. Rather than creating an empty list and appending 100 elements to it, we can convert a
object to a list with
#a list with 100 elements my_list = list(range(100)) print(my_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 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, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Inclusive and Exclusive range argument
Whether we are using one, two, or all three arguments in the range function, the value of the start argument will be inclusive and end exclusive.
For instance, the
sequence will start from 0 & end at 9, 10 will be excluded. Another example, the
range(10, 20, 2)
sequence will start at 10 and ends at 18, excluding 20. To include the end value we need to add 1 to the end value.
for i in range(10, 20+1, 2): print(i,end=" ")
10 12 14 16 18 20
Concatenate the two range function sequence
Suppose you have two range function objects containing different range sequences and wish to concatenate both sequences as a single sequence. let say you wish to concatenate
range(3, 10, 2)
, for this, you can take the help of an inbuilt itertools module chain method. The
method accepts iterable objects as arguments and chains them into a single iterable object.
from itertools import chain #concatenate two range sequences concatenated = chain(range(3), range(3,10, 2)) for i in concatenated: print(i, end =" ")
0 1 2 3 5 7 9
range() function and slicing
Similar to the list, tuple, and string, we can perform indexing and slicing on the range object.
indexing on the range object
With indexing, we can access an individual item from the range object sequence.
>>> range(10) 2 >>> range(10) 1 >>> range(10) 5
We can also perform the negative indexing on the range object.
>>> range(10)[-2] 8 >>> range(10)[-1] 9 >>> range(10)[-5] 5
slicing on the range object
When we slice a range object using the slicing syntax, it returns a range object sequence.
range_slice = range(10)[2:7] print(slice) #<class 'slice'>
We can iterate over the returned sliced range object like a normal range object.
range_slice = range(10)[2:7] for i in range_slice: print(i, end=" ")
2 3 4 5 6
Note: In range indexing and slicing if we use any index number out of the sequence range we will recive the error IndexError: range object index out of range.
range() over characters and alphabets
characters and alphabets are represented as strings in Python, and if we use string data type in the range function such as
we receive the TypeError. In order to perform the range function on Python characters, we first need to convert the character to its equivalent integer ASCII code using the
function, form a range object using that ASCII code, and convert that ASCII code back to the character using the
Let's create a range sequence from a to z using the range function.
a_ascii = ord('a') z_ascii = ord('z') for i in range(a_ascii,z_ascii+1): print(chr(i), end=" ")
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
As a Python developer, you will often use the range function in your scripts. The range function is mostly used with the
a loop when we want to execute a code of block repeatedly up to a certain number of times. It is also used when we want to loop over a list, tuple, and string using their index numbers. The Python range function returns a range object which also contains some properties like
, that return the start, end, and step argument values of the object.
Python Range Interview Questions
Question: Does range() function always start from 0?
No, it only starts from 0 if we pass only one argument to the range function. For example,
the sequence starts from 0 and ends at 8. And if we pass two or 3 arguments to the range function, the sequence will start from the specified start point.
Question: What is the return value of the range() function in Python?
function returns an iterable
Question: Are range and list are same in Python?
No, both are different data objects, a
is a function, and a list is a data structure. But we can convert a sequence of range numbers into integers using the list() function.
Question: How to find the total sum of a range sequence?
Answer: We can apply the sum() function on the range object example, sum(range(10)) will return 45, which is the sum of the first 10 numbers from 0 to 9.
People are also reading:
Leave a Comment on this Post