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:
If you want to divide a list of numbers divided into the first number,
you can do the following:
nbrlist = [48, 8, 2]
#You want the 2nd number onward divided into the first number
finaldiv = nbrlist[0] #The first number
for nbr in nbrlist[1:]: #The list starting from the 2nd number to the end
finaldiv /= nbr
print(finaldiv)
which outputs 3.0
divide all elements of a list by 5 and I need a list of elements with quotient 0 Elements