How can I multiply all items in a list together with Python?

user1897814 picture user1897814 · Dec 12, 2012 · Viewed 252.8k times · Source

I need to write a function that takes a list of numbers and multiplies them together. Example: [1,2,3,4,5,6] will give me 1*2*3*4*5*6. I could really use your help.

Answer

rich tier picture rich tier · Dec 12, 2012

Python 3: use functools.reduce:

>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Python 2: use reduce:

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

For compatible with 2 and 3 use pip install six, then:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720