How to add two consecutive number in the list.
l = [1,2,3,4,5,6,7,8,9]
result = [3,7,11,15,9]
l = [1,2,3,4,5,6,7,8,9,10]
result = [3,7,11,15,19]
I can easily achieve it using simple for loop. But How can I achieve it using more pythonic way.
import itertools as it
[sum(r) for r in it.izip_longest(l[::2], l[1::2], fillvalue=0)]
returns awaited values for both odd and even numbers:
l = [1,2,3,4,5,6,7,8,9] # [3, 7, 11, 15, 9]
l = [1,2,3,4,5,6,7,8,9,10] # [3, 7, 11, 15, 19]
UPDATE: if the original list is really large, you can replace the simple slices with islice
:
[sum(r) for r in it.izip_longest(it.islice(l,0,None,2), it.islice(l,1,None,2), fillvalue=0)]
UPDATE 2: even a shorter and more universal version (without itertools) comes here:
l = [1,2,3,4,5,6,7,8,9,10]
n = 3
[sum(l[i:i+n]) for i in xrange(0, len(l), n)]
# returns: [6, 15, 24, 10]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With