Reputation: 43
I'm trying to write a function that will return a list that is made up of the sum of n integers in a list. I know that sounds confusing.
For example :
List = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
n = 5
the function should return [15,40,65]
I have a for loop created right now but it keeps using a preceding term that I don't want it to so the sum is always incorrect.
Any help would be appreciated!
Upvotes: 0
Views: 107
Reputation: 251051
Use a list comprehension and slicing:
>>> lis = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
>>> n = 5
>>> [sum(lis[i:i+n]) for i in xrange(0, len(lis), n)]
[15, 40, 65]
Upvotes: 6