4
list_ = [(1, 2), (3, 4)]

What is the Pythonic way of taking sum of ordered pairs from inner tuples and multiplying the sums? For the above example:

(1 + 3) * (2 + 4) = 24
asked Jan 4, 2016 at 14:34
2
  • 1
    What happens if there are 3 tuples: list_ = [(1,2), (3,4), (5,6)]? Commented Jan 4, 2016 at 14:54
  • @erip (1+3+5) * (2+4+6) = 108 Commented Jan 4, 2016 at 18:02

2 Answers 2

7

For example:

import operator as op
import functools
functools.reduce(op.mul, (sum(x) for x in zip(*list_)))

works for any length of the initial array as well as of the inner tuples.

Another solution using numpy:

import numpy as np
np.array(list_).sum(0).prod()
answered Jan 4, 2016 at 14:37
14
  • @PeterWood Sure, why not? Commented Jan 4, 2016 at 14:42
  • 2
    @erip because reduce was removed from python 3: docs.python.org/3.0/whatsnew/3.0.html#builtins Commented Jan 4, 2016 at 14:44
  • 1
    @eumiro just to add to the available options: rather than importing operator.mul, lambda x, y: x * y works fine also. Although really there is nothing wrong with op.mul to begin with :). Commented Jan 4, 2016 at 14:45
  • @kazemakase: thank you for the reduce info - I have updated the answer. Commented Jan 4, 2016 at 14:45
  • 1
    @blackened: how about functools.reduce(op.mul, (sum(x) for x in list(zip(*list_))[:-1])) ? Commented Jan 5, 2016 at 14:06
0

If the lists are small as is implied, I feel that using operator and itertools for something like this is applying a sledgehammer to a nut. Likewise numpy. What is wrong with pure Python?

result = 1
for s in [ sum(x) for x in zip( *list_) ]: 
 result *= s

(although it would be a lot nicer if pure Python had a product built-in as well as sum ). Also if you are specifically dealing only with pairs of 2-tuples then any form of iteration is a sledgehammer. Just code

result = (list_[0][0]+list_[1][0] )*( list_[0][1]+list_[1][1])
answered Jan 4, 2016 at 15:29
3
  • 1
    You could also argue that using zip(*) is a sledgehammer when you could just do it with pure python. Using reduce simply does the same thing your code does but more concise Commented Jan 5, 2016 at 3:52
  • Yes, reduce is a built-in as well as zip so its just that I personally find this way easier to read. Commented Jan 5, 2016 at 14:58
  • Actually my previous is wrong. zip is a Python 3 built-in but reduce is not, so my way is Python 2/3 agnostic. Commented Jan 5, 2016 at 15:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.