261

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

I'm pretty sure such a function exists, but I can't find it.

0

9 Answers 9

236

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)
10
  • 7
    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.
    – the911s
    Mar 5, 2014 at 21:30
  • 22
    Isn't Guido also the guy who doesn't like reduce? Oct 2, 2015 at 5:48
  • 3
    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.
    – ojrac
    Oct 13, 2015 at 19:56
  • 13
    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. Jul 18, 2016 at 17:02
  • 2
    @PatrickMcElhaney It sounds like python3 already got rid of the reduce builtin. I think product missed its chance. ;)
    – ojrac
    Jul 26, 2016 at 14:27
144

Update:

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.

1
  • 2
    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.
    – Veky
    Feb 15, 2019 at 6:07
48

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

4
  • 4
    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.
    – Jason S
    Nov 13, 2015 at 17:38
  • 2
    @JasonS np.prod(arange(1,14, dtype='object'))?
    – endolith
    Apr 26, 2016 at 4:09
  • 1
    The math.prod() function will make this answer obsolete.
    – Benoît P
    Feb 26, 2019 at 16:11
  • 1
    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().
    – RCross
    Feb 6, 2020 at 16:11
43

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?

8
  • 9
    If using Python 3 use functools.reduce instead of reduce. Oct 29, 2015 at 17:25
  • 3
    For even more functools fun: prod = functools.partial(functools.reduce, operator.mul)
    – bukzor
    Dec 29, 2018 at 1:47
  • So in Python 3 I need two imports to do something so basic?!
    – A. Donda
    Jul 18, 2021 at 9:54
  • @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. Dec 9, 2021 at 22:36
  • @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.
    – A. Donda
    Dec 18, 2021 at 17:59
29
Numeric.product 

( or

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

)

6
  • He wants a function he can load from a module or library, not writing the function himself.
    – Jeremy L
    Feb 27, 2009 at 16:10
  • 3
    But if there isn't one, he probably still wants the function.
    – DNS
    Feb 27, 2009 at 16:14
  • 2
    Right, but he needs to know one doesn't exist, since that's his main question.
    – Jeremy L
    Feb 27, 2009 at 16:16
  • 2
    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. Apr 10, 2013 at 1:23
  • 3
    @CraigMcQueen Numeric is (one of) the predecessors of numpy.
    – tacaswell
    Mar 24, 2015 at 0:46
24

Use this

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

Since there's no built-in prod function.

6
  • 6
    you must think reduce really is an antipattern :) Feb 27, 2009 at 16:12
  • 2
    He wanted to know if an existing function exists that he can use.
    – Jeremy L
    Feb 27, 2009 at 16:12
  • And this answer explainss that there isn't one.
    – EBGreen
    Feb 27, 2009 at 16:14
  • 6
    @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
    Feb 27, 2009 at 16:14
  • @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. Oct 24, 2018 at 4:27
8

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

import numpy 
prod_sum = numpy.prod(some_list)
1
  • 3
    That's dangerously close to a "works on my machine" statement! Numpy, lovely though it is, is unequivocaly not a builtin.
    – RCross
    Feb 6, 2020 at 16:10
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]
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.