0
[('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2',
'4.2', '4.3', ' \n')]

How can I sum up the values from position [1] to [12]?

1
  • note that the solutions mention your_list[0] to reference the tuple that is the first elements of your list (I'm not sure if this was intended or not) Commented Jan 25, 2011 at 0:59

4 Answers 4

3

Convert to float and sum using a list comprehension:

sum(float(x) for x in my_list[0][1:13])

edit: eeks, range was wrong. edited per comments.

Sign up to request clarification or add additional context in comments.

1 Comment

careful, this one only sums from position 1 to 11!
2
L=[('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2', '4.2', '4.3', ' \n')]
sum(map(float,L[0][1:13]))

Comments

1

If you want to avoid creating an extra temporary list, you can use islice

>>> from itertools import islice
>>> L=[('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2', '4.2', '4.3', ' \n')]
>>> sum(map(float,islice(L[0],1,13)))
62.5

Comments

0

You could use a lambda and reduce.

lst = [('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2', '4.2', '4.3', ' \n')]

lst_sum = reduce(lambda x, y : float(x) + float(y), lst[0][1:12])

1 Comment

don't use sum as a variable name as it clashes with the builtin function sum - which coincidentally does the same job as the reduce+lambda. I think the OP expects the items to be added as floats, not as strings

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.