Diego Asked: 2020-09-25 14:25:07 +0800 CST 2020-09-25 14:25:07 +0800 CST 2020-09-25 14:25:07 +0800 CST Multiply all numeric elements within an array 772 We have for example the array: [1,2,5,7,12,3,9] How could I multiply all the elements of the array without using a for loop? python 4 Answers Voted Best Answer Rostan 2020-09-25T14:57:07+08:002020-09-25T14:57:07+08:00 What you need is to make use of numpy, it has a method known as prod which multiplies all the elements inside an array. << import numpy as np << a = [1,2,3,4] << print(np.prod(a)) >> 24 I hope my answer has served you, greetings. adevel 2020-09-25T15:27:31+08:002020-09-25T15:27:31+08:00 Without numpy it would be: import operator import functools functools.reduce(operator.mul, [1,2,5,7,12,3,9]) You can see the reduce documentation: https://docs.python.org/2/library/functions.html#reduce It basically executes a two-argument function cumulatively on a list of elements, in this case mul, but you can use other "function-like operators" like "sub" or "add", full list here https://docs. python.org/2/library/operator.html#operator.mul aeportugal 2020-09-25T15:24:20+08:002020-09-25T15:24:20+08:00 Another way to do it, without using numpy: >>> from functools import reduce >>> items = [1,2,5,7,12,3,9] >>> reduce(lambda x, y: x*y, items) 22680 Javier Cárdenas 2020-09-25T18:35:45+08:002020-09-25T18:35:45+08:00 It's not very Pythonic, but this option doesn't use for-loop: arr = [1,2,5,7,12,3,9] i = 0 prod = 1 while i < len(arr): prod = prod * arr[i] i += 1 print(prod)
What you need is to make use of numpy, it has a method known as prod which multiplies all the elements inside an array.
I hope my answer has served you, greetings.
Without numpy it would be:
You can see the reduce documentation: https://docs.python.org/2/library/functions.html#reduce
It basically executes a two-argument function cumulatively on a list of elements, in this case mul, but you can use other "function-like operators" like "sub" or "add", full list here https://docs. python.org/2/library/operator.html#operator.mul
Another way to do it, without using numpy:
It's not very Pythonic, but this option doesn't use for-loop: