276

Python's sum() function returns the sum of numbers in an iterable.

sum([3,4,5]) == 3 + 4 + 5 == 12

I'm looking for the function that returns the product instead.

somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
Pat Myron
4,6664 gold badges30 silver badges52 bronze badges
asked Feb 27, 2009 at 16:06
0

10 Answers 10

244

Historically, Guido vetoed the idea: http://bugs.python.org/issue1093

As noted in that issue, you can make your own:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
reduce(operator.mul, (3, 4, 5), 1)
answered Feb 27, 2009 at 16:13
Sign up to request clarification or add additional context in comments.

9 Comments

Here is a great example of where there is a "need for this," to quote Guido: product(filter(None, [1,2,3,None])). Hopefully it will be included someday.
Isn't Guido also the guy who doesn't like reduce?
Yep -- and reduce is no longer even a builtin in Python 3. IMO, we don't need every possible list operator added to the global builtins when a standard (or 3rd party) library would do. The more builtins you have, the more common words become off-limits as local variable names.
Just found this nugget in Guido's blog post about reduce(). "We already have sum(); I'd happily trade reduce() for product()...". If anyone wants to petition for including product() in the standard library, the number of views on this question may help make the case.
@PatrickMcElhaney It sounds like python3 already got rid of the reduce builtin. I think product missed its chance. ;)
|
165

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce # Required in Python 3
import operator
def prod(iterable):
 return reduce(operator.mul, iterable, 1)
>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math
>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp
>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993
>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

mkrieger1
24.2k7 gold badges69 silver badges85 bronze badges
answered Feb 6, 2018 at 17:32

2 Comments

You might want to add that the floats in the last example need to be positive. Otherwise, you might have to use cmath, but even then it won't really work in all cases.
Another special case is the evaluation of a given prime factorization. Today I found a divergence in the factorizations of 2**127-1 given by GPT-4o mini and primefac and math.prod helped me a lot.
49

There's a prod() in numpy that does what you're asking for.

istruble
13.8k2 gold badges51 silver badges54 bronze badges
answered Jun 15, 2011 at 21:33

4 Comments

note: doesn't support Python longs (arbitrary precision integers) so np.prod(range(1,13)) gives the correct answer equal to 12! but np.prod(range(1,14)) does not.
@JasonS np.prod(arange(1,14, dtype='object'))?
The math.prod() function will make this answer obsolete.
Still tedious to have to import math when you want to do this in a simple one-liner. I miss reduce() and the Guido-rejected product().
45

There isn't one built in, but it's simple to roll your own, as demonstrated here:

import operator
def prod(factors):
 return reduce(operator.mul, factors, 1)

See answers to this question:

Which Python module is suitable for data manipulation in a list?

answered Feb 27, 2009 at 16:11

8 Comments

If using Python 3 use functools.reduce instead of reduce.
For even more functools fun: prod = functools.partial(functools.reduce, operator.mul)
So in Python 3 I need two imports to do something so basic?!
@A.Donda You need to use imports in Python to do far more basic things: the square root function is in Math, Threads are in threading, etc etc. Python doesn't eschew namespaces, it's actually an explicit part of the Zen of Python that it embraces them.
@MarcelBesixdouze, yes, I agree that namespaces are one honking great idea. But imho in a language that has native lists, multiplying a bunch of numbers should be a builtin. And I consider it to be more basic than square roots and threading. In particular the latter is complex enough to warrant a module.
|
29
Numeric.product 

( or

reduce(lambda x,y:x*y,[3,4,5])

)

answered Feb 27, 2009 at 16:09

5 Comments

He wants a function he can load from a module or library, not writing the function himself.
But if there isn't one, he probably still wants the function.
You also have to give reduce a default value of 1 otherwise it will fail in the null case. The product of an empty sequence is defined as 1.
@CraigMcQueen Numeric is (one of) the predecessors of numpy.
An example of how to use Numeric.product, and how to import it, would make this answer even better!
24

Use this

def prod(iterable):
 p = 1
 for n in iterable:
 p *= n
 return p

Since there's no built-in prod function.

wim
369k114 gold badges682 silver badges822 bronze badges
answered Feb 27, 2009 at 16:10

5 Comments

you must think reduce really is an antipattern :)
He wanted to know if an existing function exists that he can use.
@zweiterlinde: For beginners, reduce leads to problems. In this case, using lambda a,b: a*b, it isn't a problem. But reduce doesn't generalize well, and gets abused. I prefer beginners not learn it.
@S.Lott I've never seen any beginners use reduce, much less any other functional-esque constructs. Heck, even "intermediate" programmers usually don't know much beyond a list comprehension.
FWIW this is about 25~30% faster than the reduce-based solution
8

Perhaps not a "builtin", but I consider it builtin. anyways just use numpy

import numpy 
prod_sum = numpy.prod(some_list)
answered Feb 10, 2019 at 23:17

1 Comment

That's dangerously close to a "works on my machine" statement! Numpy, lovely though it is, is unequivocaly not a builtin.
4

I prefer the answers a and b above using functools.reduce() and the answer using numpy.prod(), but here is yet another solution using itertools.accumulate():

import itertools
import operator
prod = list(itertools.accumulate((3, 4, 5), operator.mul))[-1]
answered Nov 30, 2017 at 18:55

Comments

1

You can also encode your list of numbers as a pd.Series and then use pd.Series.product():

>>> import pandas as pd
>>> pd.Series([5,3,-1]).product()
-15
answered Sep 11, 2022 at 11:33

Comments

1

If you don't want to import anything:

eval("*".join([str(num) for num in list_of_numbers]))
answered Sep 19, 2024 at 6:30

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.