Python range() Function: Float, List, For loop Examples

What is Python Range?

Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value by 1 till the stop index.

For example range(5) will output you values 0,1,2,3,4 .The Python range()is a very useful command and mostly used when you have to iterate using for loop.

Syntax

range(start, stop, step)

Parameters

  • start: (optional) The start index is an integer, and if not given, the default value is 0.
  • stop: The stop index decides the value at which the range function has to stop. It is a mandatory input to range function. The last value will be always 1 less than the stop value.
  • step: (optional).The step value is the number by which the next number is range has to be incremented, by default, it is 1.

Return value

The return value is a sequence of numbers from the given start to stop index.

Python range() Function and history

Python range() has been introduced from python version 3, before that xrange() was the function.

Both range and xrange() are used to produce a sequence of numbers.

Following are the difference between range and xrange():

range() xrange()
The range() gives the sequence of numbers and returns a list of numbers. The xrange() function gives a generator object that needs to be looped in a for-loop to get the values.
The range() returns a list. xrange() returns a generator object.
The range() method uses more memory as the list returned has to be stored in comparison to xrange(). As xrange() returns a generator object, it does not give values instantly and has to be used inside for-loop to get the values.
The usage of memory is more hence the code execution is slow when working on a huge set of data. The code execution is faster using xrange().

Using range()

This example shows how to print the values from 0-9 using range().

The value used in range is 10, so the output is 0 1 2 3 4 5 6 7 8 9

Since the start is not given the start is considered as 0 and the last value is given till 9. The last value is always 1 less than the given value i.e. stop-1.

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

Output:

0 1 2 3 4 5 6 7 8 9

Using start and stop in range()

In the code, the start value is 3, and stop value is 10. Here the start index is 3, so the sequence of numbers will start from 3 till the stop value. The last value in the sequence will be 1 less than the stop value 10-1 = 9.

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

Output:

3 4 5 6 7 8 9

Using start, stop and step

The start value is 3, so the sequence of numbers will start at 3. The stop value is 10, so the sequence of numbers will stop at (10-1) i.e 9. The step is 2, so each value in the sequence will be incremented by 2. If the step value is not given, the value for step defaults to 1.

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

Output:

3 5 7 9

So far, we have seen how range() function gives the incremented value for the stop value given. Let us now try an example to get the decremented value in the range given.

Incrementing the values in range using a positive step.

The parameter step in range() can be used to increment /decrement the values. By default, it is a positive value 1. So it will always give incremented values.

The step value has to be positive incase you want to want incremented values as ouput.

for i in range(1, 30, 5):
    print(i, end =" ")

Output:

1 6 11 16 21 26

Reverse Range: Decrementing the values using negative step

The parameter step with negative value in range() can be used to get decremented values. In the example below the step value is negative so the output will be in decremented from the range value given.

for i in range(15, 5, -1):
    print(i, end =" ")

Output:

15 14 13 12 11 10 9 8 7 6

The start value is 15, the stop value is 5 and the step value is negative number i.e -1. With above inputs range() function will decrement the value from 15 onwards till it reaches the stop value , but here the difference is the last value will be stop + 1.

Using floating numbers in Python range()

Let us now work on the range() using floating-point numbers.

Example:

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

In above example we have used stop value as 10.5.

The output is :

Traceback (most recent call last):
  File "python_range.py", line 1, in <module>
    for i in range(10.5):
TypeError: 'float' object cannot be interpreted as an integer

Python gives an error as the range() function does not support floating-point numbers for start, stop and step.

Using for-loop with Python range()

In this example we will use a array of numbers and, let us see how to use the iterate the array inside for-loop using range()

Example:

arr_list = ['Mysql', 'Mongodb', 'PostgreSQL', 'Firebase']

for i in range(len(arr_list)):
    print(arr_list[i], end =" ")

Output:

MysqlMongodb PostgreSQL Firebase

In above example we have used len(arr_list) as the stop value. The for loop will iterate till the stop value i.e the length of the array and that will be 4, as we have four items in the arr_list. The start value will be 0 and step will be 1.So the values will start from 0 and will stop at 3 i.e length of array -1 meaning 4 -1 = 3.

Using Python range() as a list

In this example will see how to make use of the output from range as a list.

Example:

print(list(range(10)))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can see the output is a list format. It was not necessary to loop the range() and using list() method we could directly convert the output from range to list format.

Using characters in python range()

So far, we have used integers in python range(). We have also seen that floating-point numbers are not supported in python range. Let us try and see the output as to what happens when we use characters.

Example:

for c in range ('z'):
        print(c, end =" ")

Output:

Traceback (most recent call last):
  File "python_range.py", line 1, in <module>
    for c in range ('z'):
TypeError: 'str' object cannot be interpreted as an integer

It throws an error saying a string cannot be interpreted as an integer.

To get the list of the alphabets you can customize the code and get the desired outputas shown below:

Example:

def get_alphabets(startletter, stopletter, step):
    for c in range(ord(startletter.lower()), ord(stopletter.lower()), step):
        yield chr(c)

print(list(get_alphabets("a", "h", 1)))

Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g']

How to Access Range Elements

You can make use of a for-loop to get the values from the range or use the index to access the elements from range().

Using for-loop

Example:

for i in range(6):
    print(i)

Output:

0
1
2
3
4
5

Using index

The index is used with range to get the value available at that position. If the range value is 5, to get the startvalue, you can use range(5)[0] and the next value range(5)[1] and so on.

Example:

startvalue = range(5)[0] 
print("The first element in range is = ", startvalue) 

secondvalue = range(5)[1] 
print("The second element in range is = ", secondvalue) 

lastvalue = range(5)[-1]
print("The first element in range is = ", lastvalue)

Output:

The first element in range is =  0
The second element in range is =  1
The first element in range is =  4

Using list()

This method will print all the elements from the range(). Using list() it will return the elements from range() in list format.

Example:

print(list(range(10)))

Output:

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

It gives the list output for the range given.

Example: Get even numbers using range()

Using range() will get the list of even numbers in the range given as input. The parameters for range() are, start is 2, stop is 20, and step is 2, so the values will be incremented by 2 and will give even numbers till stop-2.

Example:

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

Output:

2 4 6 8 10 12 14 16 18

Merging two-range() outputs

In this example will concatenate 2 range() functions with the help of itertools module chain() function.

Example:

from itertools import chain 

print("Merging two range into one") 
frange =chain(range(10), range(10, 20, 1))
for i in frange: 
    print(i, end=" ")

Output:

Merging two range into one
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Using range() With NumPy

The NumPy module has arange() function that works and gives similar output like range(). The arrange() takes in the same parameters like range().

Syntax:

arange(start, stop, step)

To work with NumPy follow the steps given below.

Step 1: Import NumPy module

import numpy

Incase while execution, it gives an error saying numpy module not found, you need to install the module as shown in step 2.

Step 2: Install NumPy

pip install numpy

Step 3: Working Example of arange() using NumPy

import numpy as np 

for  i in np.arange(10):
   print(i, end =" ")        

Output:

0 1 2 3 4 5 6 7 8 9

Floating point numbers using NumPy arange()

It is not possible to get the floating point sequence using range(), but it is possible using NumPy arange().

Example:

The range that we want is from 0.5 to 1.5. The value will be increment by 0.2.

import numpy as np 

for  i in np.arange(0.5, 1.5, 0.2):
   print(i, end =" ")        

Output:

0.5 0.7 0.8999999999999999 1.0999999999999999 1.2999999999999998

The output we get is a little weird,some of the float numbers are shown with 16 decimal places. This happens because of the complexity of storing decimal floating numbers into binary format. You can also round the values if required and limit them to the decimal places you need.

Summary

  • Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value till the stop index.
  • Python range() has been introduced from python version 3, prior to that xrange() was the function.
  • The range() gives the sequence of numbers and returns a list of numbers. The xrange() function gives a generator object that needs to be looped in a for-loop to get the values.
  • The parameter step in range() can be used to increment /decrement the values. By default, it is a positive value 1. So it will always give incremented values.
  • Python gives an error for floating-point numbers as the range() function supports only integer values.
  • The values from range() can be accessed using for-loop, using index and list()
  • The NumPy module has arange() function that works and gives similar output like range(). The arange() takes in the same parameters as range().
  • It is possible to get the floating-point sequence NumPy arange() that is not supported using range().