2

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.

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • 2
    Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. StackOverflow is not a coding or tutorial service. – AChampion May 08 '17 at 15:40

5 Answers5

3

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
>>> 
  • 1
    answers with code are enhanced by explanation of what the code does. Explaining your code will help future users understand what's going on, and adapt your answer to their own needs. – Mohammad Athar May 08 '17 at 15:53
1

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)
keepAlive
  • 6,369
  • 5
  • 24
  • 39
0
>>> 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

AChampion
  • 29,683
  • 4
  • 59
  • 75
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Note: `reduce` is in `functools` in py3. And you can subtract one in the reduce: `reduce(lambda x, y: x*(y-1), l, 1)`. – AChampion May 08 '17 at 15:42
0

There are many ways to multiply all the elements of an iterable.

So, given a list a you can, for example:

Use numpy:

prod([x-1 for x in a])

Use lambda and functools

functools.reduce(lambda x, y: x*y, [x-1 for x in a])

Do it manually

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()?

Community
  • 1
  • 1
Juan T
  • 1,219
  • 1
  • 10
  • 21
-1
result = 1
for x in p:
    result *= x - 1
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • 1
    Your answer got flagged as low quality; possibly because you haven't explained how or why this answers the question. I assume the downvote came from the low quality queue. – Ben May 08 '17 at 18:16
  • 1
    @Ben Ok, that might explain it. Morons who can't be bothered to read the question and think that even the most obvious and self-explanatory code needs to be diluted with extra text... – Stefan Pochmann May 08 '17 at 18:19
  • Or it might be related to python not supporting "*=" and the like operators? – Helen Aug 21 '22 at 12:04