tags:

views:

1534

answers:

5

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.

+5  A: 
Numeric.product

( or

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

)

Steve B.
He wants a function he can load from a module or library, not writing the function himself.
Nerdling
But if there isn't one, he probably still wants the function.
DNS
Right, but he needs to know one doesn't exist, since that's his main question.
Nerdling
+3  A: 

Use this

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

Since there's no built-in prod function.

S.Lott
you must think reduce really is an antipattern :)
zweiterlinde
He wanted to know if an existing function exists that he can use.
Nerdling
And this answer explainss that there isn't one.
EBGreen
@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
wouldn't it be better for consistency to have similar-to-sum single iterable as an input?
SilentGhost
@SilentGhost: good point.
S.Lott
+1  A: 

If Python had one it would be called product(), unfortunately it doesn't. You can do something like Steve B. mentioned.

Ben S
+16  A: 

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

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

See answers to this question:

http://stackoverflow.com/questions/493853/which-python-module-is-suitable-for-data-manipulation-in-a-list

zweiterlinde
+1 cleanest answer
Andrew Hare
+32  A: 

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

But, as noted in that issue, you can make one pretty easily:

import operator
reduce(operator.mul, (3, 4, 5))
ojrac