Dan
Dan

Reputation: 8513

Adding values in a tuple that is in a list in python

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.

Upvotes: 3

Views: 1255

Answers (3)

Shekhar
Shekhar

Reputation: 7235

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

Upvotes: 0

YOU
YOU

Reputation: 123831

>>>> 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

Upvotes: 7

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

>>> 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

Upvotes: 4

Related Questions