0

My question is based on an earlier question and I can't find to figure out (nor find) the subsequent step I need.

Say I do have the same list of tuples, namely:

[(0, 1), (2, 3), (5, 7), (2, 1)]

Also I wish to find the sum of the first values in each pair, which could be done by the simple pythonic:

sum([pair[0] for pair in list_of_pairs]) 

as provided by David Z. However, in my case I only wish to sum from the first first value up until a following first value, say the first value at index N = 2. Thus, only calculate the sum of:

0 + 2 + 5 

I have been trying things like:

sum([pair[0] for pair in list_of_pairs[:N])

but without success. Can anyone provide me with an elegant solution?

Community
  • 1
  • 1
Steyn W.
  • 86
  • 8

1 Answers1

0

you were very close to the solution

This works for me :

N=2

sum([pair[0] for pair in list_of_pairs[0:N+1]]) 

If you wants from middle then you can do this :

N=3
M=1
print sum([pair[0] for pair in list_of_pairs[M:N+1]]) 
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45