Divide all elements of a list by a number in Python

In this tutorial, we are going to learn how to divide the elements of a list in Python. As we know that in List we can store elements like int, float, string, etc. As we know that string can not be divided by a number. To divide elements of a list, all the elements should be either int or float. So let’s start.

How to divide all elements of a list by a number in Python

To divide all the elements, we will generate a random list containing int and float values.
Let us generate a random list.

List=[5,10.5,15,20.5,25]

Now we would like to divide each of the elements by 5.
We can divide using “for loop”. Let us see how.

num = 5
new_List = [i/num for i in List]
print(new_List)

Output–

[1.0, 2.1, 3.0, 4.1, 5.0]

We can also divide each element using numpy array. As we know, to use numpy, we have to import numpy. Then we can perform numpy.
Let us see an example taking the above list.

import numpy as np
List = [5,10.5,15,20.5,25]
num = 5
new_List  = np.divide(List, num)
print(new_List)

Output–

[1.0, 2.1, 3.0, 4.1, 5.0]

You may also read:

Leave a Reply

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