tags:

views:

120

answers:

3

I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]

Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18.

+3  A: 
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> s = sum(i[0] for i in l)
>>> print s
18
Max Shawabkeh
what if the tuples have numbers more than 1 digit? it wouldnt matter would it?
Dan
If they have more than one digit in a single number, it'll work fine. If they have more than one number, go with S.Mark's answer.
Max Shawabkeh
+7  A: 
>>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]

>>> sum(map(sum,l))
18

>>> l[0]=(1,2,3,)
>>> l
[(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(map(sum,l))
23
S.Mark
A: 

Just some fun with itertools, not very readable. Works only if you consider 1st element in tuple.

>>> import itertools
>>> l = [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]
>>> sum(*itertools.izip(*l))
18
Shekhar