Search code examples
pythonlistmathoperator-keywordmultiplication

How do I multiply all the elements inside a list by each other?


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?


Solution

  • 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)