« June 2011 | Main | April 2012 »

February 02, 2012

Calculating the product of a Python list

I came across a stackoverflow question about multiplying the numbers in a Python list. Suggestions there included:

def product(list):
    p
= 1
   
for i in list:
        p
*= i
   
return p

and

from operator import mul
reduce
(mul, list)

You can also do:

import math
math
.exp(sum(map(math.log, list)))

It's not as readable as the reduce-based solution, though if you're a mathematician who isn't familiar with reduce() the opposite might be true!

I wouldn't advise using the log-based solution under normal circumstances. But if you're ever in a situation where you risk overflow or overflow, such as in

>>> reduce(mul, [10.]*309)
inf

and your purpose is to compare the products of different sequences rather than to know what the products are, then

>>> sum(map(math.log, [10.]*309))
711.49879373515785

is the way to go because it's virtually impossible to have a real-world problem in which you would overflow or underflow with this approach. (The larger the result of that calculation is, the larger the product would be if you could calculate it.)

February 2, 2012 in Python | Permalink | Comments (0)