Home > Back-end >  Add two numbers next to each other in a list and return output also in list
Add two numbers next to each other in a list and return output also in list

Time:06-03

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.

CodePudding user response:

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

  • Related