Im trying to multiply all the numbers in a list by each other
a = [2,3,4]
for number in a:
total = 1
total *= number
return total
The output from this should be 24 but for some reason I get 4. Why is this the case?
Im trying to multiply all the numbers in a list by each other
a = [2,3,4]
for number in a:
total = 1
total *= number
return total
The output from this should be 24 but for some reason I get 4. Why is this the case?
You're initializing total to 1 every iteration of the loop.
The code should be (if you actually want to do it manually):
a = [2, 3, 4]
total = 1
for i in a:
total *= i
That solves your immediate problem but, if you're using Python 3.8 or higher, this functionality is in the math
library:
import math
a = [2, 3, 4]
total = math.prod(a)
Approach 1: Using the prod function from numpy package.
import numpy
...: a = [1,2,3,4,5,6]
...: b = numpy.prod(a)
In [128]: b
Out[128]: 720
Approach 2: in Python 3.8 , prod is added in the math module:
math.prod(iterable, *, start = 1)
math.prod(a)
would do the same
If you don't want to use numpy then use reduce function.
from functools import reduce
reduce(lambda x, y: x*y, [1, 2, 3, 4, 5])
The reason it's 4
is because in the for
loop, you execute total = 1
, then you multiple total
with the current number in each iteration. So it will loop till the end, the last element is 4
, and you multiple 4 to 1, so the total is 4 now.
If you want to multiple all elements in a list. I suggest you use numpy.prod
:
import numpy as np
list = [2,3,4,5]
final = np.prod(list)