📅 2010-Feb-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ arithmetic, python, sequences ⬩ 📚 Archive
Python has a built-in function to find the sum of the elements of a list:
alist = [10, 3, 8]
<strong><a href="http://docs.python.org/library/functions.html#sum">sum</a></strong>(alist) # 21
But, there are no such built-in functions for other arithmetic operations. Defining such arithmetic functions that operate on sequences like lists is easy. Here is how to write a method that gives the product of the elements of a list:
import functools
import operator
def product(seq):
"""Product of a sequence."""
return <strong><a href="http://docs.python.org/library/functools.html#functools.reduce">functools.reduce</a></strong>(<strong><a href="http://docs.python.org/library/operator.html#operator.mul">operator.mul</a></strong>, seq, 1)