i'm using Python and I have the following list A = [10,20,30,40] how can obtain a new list such as I'm adding the second element to the first, the third to the second and fourth to the third. Meaning the output would be [30,50,70].
CodePudding user response:
Can use simple list comprehension like this:
a = [10,20,30,40]
b = [a[i] a[i 1] for i in range(len(a)-1)]
b
[30, 50, 70]
CodePudding user response:
Take a look at the pairwise
recipe from the itertools
module (which will be added as a function of itertools
in 3.10). Once you've copied that, you can just do:
[x y for x, y in pairwise(A)]
or for fun with less custom code, add imports from operator import add
and from itertools import starmap
and you can make an iterator that produces the results lazily with:
starmap(add, pairwise(A)) # Wrap in list if you need a list
CodePudding user response:
a = [10,20,30,40,50]
new_list = []
for i in range(1, len(a)):
new_list.append(a[i] a[i-1])