Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Python: Product of Elements of a List

📅 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="">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="">functools.reduce</a></strong>(<strong><a href="">operator.mul</a></strong>, seq, 1)