Add two numbers next to each other in a list and return output also in list

Viewed 72

I want to add two numbers to the list next to each other and return the final answer in a list using python. for example my_list = [1,2,3,5,6] And the final list will be [1,3,5,8,11] for the first digit I will consider the initial value as 0.

I tried this way to get the answer

list1 = [1,2,3,0,5,6]

first_value = 0
    new_list = []
    for i,each_value in enumerate(list1):
        if i == 0:
            sum = first_value + each_value
           
        else:
            sum = each_value + prev_val
        new_list.append(sum)
        #i = i+1
        prev_val = each_value
    print(new_list)
        

I have got the output that I want but I wanted to know can we write the same code with less number of lines either by using lambda or some python collection.

3 Answers

You can use a simple zip + map/sum:

my_list = [1,2,3,5,6]

out = list(map(sum, zip([0]+my_list, my_list)))

output: [1, 3, 5, 8, 11]

Or with itertools.pairwise (python ≥ 3.10):

from itertools import pairwise

out = my_list[:1]+list(map(sum, pairwise(my_list)))

Try this.

l = [1,2,3,5,6]

def sum_(l):
    return list(map(lambda e:l[e]+l[e-1] if e!=0 else l[e], range(len(l))))
    

print(sum_(l))

OUTPUT [1, 3, 5, 8, 11]

Explanation

I suggest After reading this you need to take a look at the map function.
  1. I give the map function two parameters one of them is range(len(l)) If you try to print In the above case this will output to range(0,5) Try to transform this into the list list(range(len(l))) this will output [0,1,2,3,4].

  2. Map function is iterated through this list and set the value of e(provide this is a parameter in lambda function. You can change it to any other name.)

  3. In line map(lambda e:l[e]+l[e-1] if e!=0 else l[e]. Here I am matching if e is not equal to 0, Because if e is 0 then e-1 is -1 which will point to the last element of the list Which will cause the code to output the wrong output.

  4. In my code if e equals 0 then this will return lst[e] else this will return the lst[e]+lst[e-1].

I hope this will explain this .

In python3.10+, I like to do this:

>>> from itertools import pairwise, starmap
>>> from operator import add
>>> lst = [1, 2, 3, 5, 6]
>>> out = lst[:1]
>>> out.extend(starmap(add, pairwise(lst)))
>>> out
[1, 3, 5, 8, 11]

Some test:

from itertools import pairwise, starmap
from operator import add
from timeit import timeit


def starmap_add_extend(lst: list):
    out = lst[:1]
    out.extend(starmap(add, pairwise(lst)))
    return out


def map_sum_extend(lst: list):
    out = lst[:1]
    out.extend(map(sum, pairwise(lst)))
    return out


def starmap_add_concat(lst: list):
    return lst[:1] + list(starmap(add, pairwise(lst)))


def map_sum_concat(lst: list):
    return lst[:1] + list(map(sum, pairwise(lst)))


def comperhension_concat(lst: list):
    return lst[:1] + [i + j for i, j in pairwise(lst)]


def generator_extend(lst: list):
    out = lst[:1]
    out.extend(i + j for i, j in pairwise(lst))
    return out


def comperhension(lst: list):
    return [val + lst[i - 1] if i else val for i, val in enumerate(lst)]


if __name__ == '__main__':
    my_lst = [1, 2, 3, 5, 6]
    for func in (
            starmap_add_extend,
            map_sum_extend,
            starmap_add_concat,
            map_sum_concat,
            comperhension_concat,
            generator_extend,
            comperhension
    ):
        print(func.__name__.ljust(20), timeit(lambda: func(my_lst)))

Output:

starmap_add_extend   0.5148536000051536
map_sum_extend       0.6762464999919757
starmap_add_concat   0.530809899995802
map_sum_concat       0.7072772000101395
comperhension_concat 0.545955400011735
generator_extend     0.7146139999968
comperhension        0.6786505000200123
Related