Sum one column of a list(follow up)

python

Solution

Generator expressions are your friend:

sum(l[-1] for l in list)

(although I do hope your list isn't literally called 'list', since that would shadow the builtin).

For the followup, it does depend on exactly what you mean by 'add all the sums that are outputted'. This could mean have some number of lists like the one you posted that you're iterating over, and you want to add all the sums together once. This would be:

sum(sum(l[-1] for l in list) for list in lists)

Or even just

sum(l[-1] for l in list for list in lists)

If you mean you want a cumulative sum - so, you want the running total at each stage as another inner sum is added to it - take a look at this previous question about cumulative sums, or just write out the loop:

cumsum = 0
for list in lists:
   cumsum += sum(l[1] for l in list)
   print(cumsum)

Problem

I have a list that that looks like this: ``` ('string ', 'time', 'SPY', 0, 0, 131.63, 100), ('sting ', 'time', 'SPY', 0, 0, 131.63, 700) ``` what I want to do is add the last column of data What I though to do is unzip the list and then sum the absolute value of the date in the last column but I cant get it to work correctly what I have been trying is this: ``` testsum = sum(abs(zip(*list[:-1])) ``` thanks EDIT: Ok so thanks for the response ``` sum(l[-1]) for l in list ``` worked well but I forgot to mention that I have it running in a for loop and what I really want to do is add all the sums that are outputted I'm really confused and am unsure how to do that I though I could do the same thing again but it didnt work

Original source

Related problems