Skip to content

Instantly share code, notes, and snippets.

@togakangaroo
Created March 8, 2020 21:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save togakangaroo/52308cb95d72da541fb1de6519019176 to your computer and use it in GitHub Desktop.

Sum elements to next in a list

Question:

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

The basic idea is to take the collection

2
4
3
1
-2

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

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

You then zip the two together into a tuple

return list(zip(lst, skipped))
2 4
4 3
3 1
1 -2

Now it's just a 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

from itertools import islice
return list(a+b for a,b in zip(lst, islice(lst, 1, None)))
6 7 4 -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment