Skip to content

Latest commit

 

History

History

sum-consecutive-elements

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Sum elements to next in a list

Question from the Operation Code Slack:

I have to create a function that sums of every 2 consecutives elements in a list. for example ([2,4,3,1,-2]). the output expected [6,7,4,-1]

So the basic idea here is to take the collection

2
4
3
1
-2

and a copy of it that same collection that skips the first element (islice is a good fit for this)

from itertools import islice
return list(islice(lst, 1, None))
431-2

You then zip the two together into a tuple.

return list(zip(lst, skipped))
24
43
31
1-2

Now it is a simple matter of iterating each tuple and adding the two elements

return list(a+b for a,b in zipped)

So putting it all together, it’s a one liner. Viola!

from itertools import islice
return list(a+b for a,b in zip(lst, islice(lst, 1, None)))
674-1