9

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?

Manas Chaturvedi
  • 5,210
  • 18
  • 52
  • 104

6 Answers6

29

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
5

You could use list comprehension.

>>> li = [(1, 2), (1, 3), (2, 3)]
>>> [x+y for (x,y) in li]
[3, 4, 5]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

Both solutions below will work.

li = [(1, 2), (1, 3), (2, 3)]
print([sum(i) for i in li])

or

def sumtupleinlist(lst):
    return [sum(i) for i in lst]
li = [(1, 2), (1, 3), (2, 3)]

To test the function, run :

print(sumtupleinlist(li))
jlewkovich
  • 2,725
  • 2
  • 35
  • 49
JAID
  • 21
  • 2
1

For beginner:

  1. Create result variable which type is list.
  2. Iterate every item from the give list by for loop.
  3. As every item is tuple so again iterate item from the step 2 and set sum of item to 0.
  4. Add sum.
  5. Append sum to result variable.

Demo:

>>> li = [(1, 2), (1, 3), (2, 3)]   # Given Input
>>> result = []                     # Step 1
>>> for i in li:                    # Step 2
...     tmp_sum = 0                 # Step 3  
...     for j in i:                 # Step 3
...         tmp_sum += j            # Step 4 
...     result.append(tmp_sum)      # Step 5 
... 
>>> print result
[3, 4, 5]

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
0
ls= [(1,2), (3,4)]
finallist = []
for tuple in ls:
     listt = list(tuple)
     summ = 0
     for m in listt:
         summ+=m
     finallist.append(summ)
print(finallist) #[3,7]
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 07 '17 at 18:44
0

make a list having tuples -

tup = [(1,2),(3,4),(5,6)]

for (a,b) in tup:
    print(a+b)

This will give you -

3
7
11
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103