I have a list like this numbers = [1, 2, 3, 4, 5]
How can I multiply all the elements of that list between themselves? Like this: 1 * 2 * 3 * 4 * 5
I have a list like this numbers = [1, 2, 3, 4, 5]
How can I multiply all the elements of that list between themselves? Like this: 1 * 2 * 3 * 4 * 5
Use functools.reduce
(<python-3.7):
>>> import functools
>>> functools.reduce(lambda x,y: x*y, [1, 2, 3, 4, 5])
120
>>>
Use math.prod
(python-3.8+):
>>> import math
>>> math.prod([1, 2, 3, 4, 5], start=1)
120
You could do this without importing libraries like this:
def multiplyList(myList):
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result
numbers = [1, 2, 3]
print(multiplyList(numbers))