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
  • 7
    You could use the SUM function directly in the database query (if supported). Commented Feb 7, 2010 at 9:06
  • 2
    Are they always (1,), you could just use len :) Commented Feb 7, 2010 at 9:37
  • Thanks for that info AndiDog, I forgot about that function Commented Feb 7, 2010 at 10:00

3 Answers 3

7
>>>> 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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

what if the tuples have numbers more than 1 digit? it wouldnt matter would it?
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.
0

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

Comments

Your Answer

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.