What is the most pythonic and elegant way to multiply the values of all elements of a list minus 1 together in Python?
I.e., calculate (p[0]-1) * (p[1]-1) * ... * (p[n-1]-1) where n is the size of the list p.
What is the most pythonic and elegant way to multiply the values of all elements of a list minus 1 together in Python?
I.e., calculate (p[0]-1) * (p[1]-1) * ... * (p[n-1]-1) where n is the size of the list p.
Use functools.reduce in python3 along with A.J.'s example:
>>> l = [5, 8, 7, 2, 3]
>>> l = [item-1 for item in l] #subtract 1
>>> functools.reduce(lambda x, y: x*y, l) #multiply each item
336
>>>
Using the numpy package
import numpy as np
np.prod(np.array(p)-1)
Or using a python built-in one, e.g. operator
reduce(operator.mul,\
map(lambda el:el-1,\
p),\
1)
>>> l = [5, 8, 7, 2, 3]
>>> reduce(lambda x, y: x*(y-1), l, 1) #multiply each item by its subtracted value
336
>>>
Thanks to @AChampion for another improvement
There are many ways to multiply all the elements of an iterable.
So, given a list a
you can, for example:
prod([x-1 for x in a])
functools.reduce(lambda x, y: x*y, [x-1 for x in a])
result=1
for x in [x-1 for x in a]: result*=a
Note that I used the list comprehension: [x-1 for x in a]
but it can also be achieved with numpy: array(a)-1
Related question: What's the Python function like sum() but for multiplication? product()?
result = 1
for x in p:
result *= x - 1