Python range() Function Explained with Examples

By | November 17, 2021
Python range() Function Explained with Examples

range() is an in-built Python function, it can generate a sequence of immutable integer numbers from the given start point up to the given end point number. It returns an iterable range object that can iterate using a for loop statement.

With for loop and range 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 for loop statement & range function, and print an integer sequence between 0 to 10.

Vamware

Example 

#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 syntax to implement a range function in a program

range Function Syntax 1

range(end)

In this syntax, the range function accepts only one argument which is mandatory.

The end argument must be an integer number, that represents the end number of the sequence that starts from 0.

return

It returns an iterable range object, which will be a sequence of integer numbers from 0 to end-1.

We can check the return type of range() function using the built-in type() function.

type(range(10))   # <class 'range'>

range(end) function Examples

Let’s see some examples of range() function with a single argument value.

Example 1

If we pass a positive integer number to the range() 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

Example 2

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

range(start, end,[step=1])

In this syntax we can pass three arguments to the range function.

  1. start : It is the integer number defining the included start point of the sequence.
  2. end: It is also the integer number argument, but it defines the excluded ending number of the sequence.
  3. step: It is the optional argument value which default value is 1. It defines the number of interval gaps between consecutive numbers of the sequence.

range() Examples

range(start, end)

When we pass two arguments to the range function, it creates an integer sequence starting from the start number and ends at end-1 .

Example

#sequence of numbers
#from 10 to 19

for i in range(10, 20):
    print(i, end=",")   

Output

10,11,12,13,14,15,16,17,18,19,

In this example, we only specified the start (10) and the end (20) arguments value to the range() function. As the step argument was optional the range function treat 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 step argument and see how it can be helpful in code.

When we pass all three arguments to the range function start, end, and steps, it generates a sequence of integer numbers from start upto end-1 with step number of the gap between two adjacent numbers.

Example

Let’s say you want to print all the even numbers between 10 to 40, there all you need to 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 =",")

Output

20,22,24,26,28,30,32,34,36,38

In this example, you can see that the range function created a sequence from 20 to 40-1, and the difference between the consecutive number was 2 that specified as the step argument.

The advantage of using the third step argument is we can also create a sequence in negative integer numbers, or in reverse order.

Example

#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,

The step argument must not be 0 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.

for loop with range()

for 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 the 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 iterate 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.

syntax

for i in range(start, end, [step]):
    #for loop body

Example

print("Multiples of 3")
for i in range(3, 31, 3):
    print(i, end =",")

Output

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 list, string, and tuples are iterable objects and for 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 loop.

In such cases, we take the help of range() function and iterate over the list with index numbers. The advantage of using range() to iterate over a list is, 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 len() function.

Let’s discuss it with a Python program.

Example

Suppose say we have a list prices, and we need to give 10% 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)

Reverse range

With the help of range() function and step 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.

  1. using the negative steps.
  2. 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 step argument, we need to make sure that the start argument value must be greater than end argument value.

Example

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 =" ")

Output

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 range_iterator that can be iterated using a for loop.

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= " ")  

Output

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= " ")

Output

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 can we use the range() function to traverse back a list.

When it comes to traversing a list of items using for loop and range function, we always use the range 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 n-1 to –1, with a step value of -1.

Example

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 =" ")

Output

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 list() function.

With the range and list functions, we can initialize a new list with a fixed size.

Example

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 range(100) object to a list with list() function.

#a list with 100 elements
my_list = list(range(100))

print(my_list)

Output

[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 range(10) 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.

Example

for i in range(10, 20+1, 2):
    print(i,end=" ")

Output

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 the sequences as a single sequence.

let say you wish to concatenate range(3) and range(3, 10, 2) as [0,1,2,3,5,7,9], for this, you can take the help of an inbuilt itertools module chain method. The chain() method accepts iterable objects as arguments and chains them into a single iterable object.

Example

from itertools import chain

#concatenate two range sequences
concatenated = chain(range(3), range(3,10, 2))

for i in concatenated:
    print(i, end =" ")

Output

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.

Example

>>> range(10)[2]
2

>>> range(10)[1]
1
>>> range(10)[5]
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.

Example

range_slice = range(10)[2:7]

for i in range_slice:
    print(i, end=" ")

Output

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 string in Python, and if we use string data type in the range function such as range('a', 'z') 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 ord() function, form a range object using that ASCII code and convert that ASCII code back to the character using chr() function.

Example

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=" ")

Output

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 

Conclusion

As a Python developer, you will often use the range function in your scripts. The range function is mostly used with the for 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 list, tuple, and string using their index numbers.

The Python range function returns a range object which also contains some properties like start, stop and step, that return the start, end, and step argument values of the object.

Python Range Interview Questions

Question: Does range() function always start from 0?

Answer: No, it only starts from 0 if we pass only one argument to the range function, for example, range(9) 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 range() function in Python?

Answer: The range() function returns an iterable range object.

Question: Are range and list are same in Python?

Answer: No, both are different data objects, a range() 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 Reply

Your email address will not be published. Required fields are marked *