ban can ban can - 11 months ago 56
Python Question

How to divide all the elements in a list together

For example:

a = [1,2,3,4,5,6]

I want to do:


I have tried using the
function but it doesn't seem to give the correct result. By the way, I am fairly new to python.


You can use reduce.

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

The code can be demonstrated as

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

which is equivalent to

>>> 1/2/3/4/5/6

As truediv has already been demonstrated by the other answer, this is an alternative (the other way is preferred) for Python2

>>> from __future__ import division
>>> l = [1,2,3,4,5,6]
>>> reduce(lambda x,y:x/y,l)