0

I am trying to create a basic Python script that allows me to multiply each number in a list and print the total.

For example, if my list contains 2, 5, 1, I want the script to multiply 2 * 5 * 1 which would give 10. For some reason, I am unable to produce this, I have been able to produce it by adding numbers together (which you can see below) but when I change line 8 to multiply, it doesn't give me the expected result (in the above example, it gives me 30 instead of the expected 10).

Incorrect multiply list total:

# input list
numbers = [2, 5, 1]
# output list
total = 0
# for each number in the list:
for number in numbers:
    # update total
    total = total + number * number
# print the total
print(total)

Script which successfully adds numbers in a list together:

# input list
numbers = [2, 5, 1]
# output list
total = 0
# for each number in the list:
for number in numbers:
    # update total
    total = total + number
# print total
print(total)
Philpot
  • 216
  • 5
  • 17

2 Answers2

2

Idiomatic way to do such things is reduce — literally to "reduce" your sequence element by element and end up with single value. If you need multiplication, you can use operator.mul — programmatic way to do multiplication:

from functools import reduce
from operator import mul

total = reduce(mul, [2, 5, 1])
Slam
  • 8,112
  • 1
  • 36
  • 44
1

To multiply the numbers in a list and print the total, you need to set the total to 1 and you need to use the *= operator. This simply means "[left hand side expression] = [itself] * [right hand side expression]"

# input list
numbers = [2, 5, 1]
# output list
total = 1
# for each number in the list:
for number in numbers:
    # update total
    total *= number
# print total
print(total)

This prints 10 (2 * 5 * 1 = 10)

Philpot
  • 216
  • 5
  • 17