Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of elements stored inside a tuple

Given a tuple containing a bunch of integer elements, how can one find the sum of all the elements?

For example, if I have a list of tuples:

li = [(1, 2), (1, 3), (2, 3)]

How can I get something like this:

[3, 4, 5]

where 3, 4 and 5 is the total sum of each of the three tuples respectively?

like image 745
Manas Chaturvedi Avatar asked Apr 06 '15 12:04

Manas Chaturvedi


1 Answers

You can use map and sum function like this

>>> li = [(1, 2), (1, 3), (2, 3)]
>>> map(sum, li)
[3, 4, 5]

Alternatively you can use list comprehension, like this

>>> [sum(tup) for tup in li]
[3, 4, 5]

Note: I personally prefer the list comprehension version, because map function in Python 3.x will return an iterable map object, which needs to be explicitly converted to a list, like this list(map(sum, li)).

>>> li = [(1, 2), (1, 3), (2, 3)]
>>> map(sum, li)
<map object at 0x7f3dc25bb0f0>
>>> type(map(sum, li))
<class 'map'>
>>> list(map(sum, li))
[3, 4, 5]

But list comprehension will give a list in both Python 2.x and Python 3.x.

like image 69
thefourtheye Avatar answered Sep 20 '22 11:09

thefourtheye