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].
Asked
Active
Viewed 51 times
3 Answers
3
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]

Shubham Periwal
- 2,198
- 2
- 8
- 26
2
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

ShadowRanger
- 143,180
- 12
- 188
- 271
1
a = [10,20,30,40,50]
new_list = []
for i in range(1, len(a)):
new_list.append(a[i] + a[i-1])
When we do range(1, len(a))
, we create a set of indexes which are [1,2,3,4].
So when we do:
for i in range(1, len(a)):
it's kind of like doing for i in range [1,2,3,4]
.
If we now imagine we are doing:
for i in [1,2,3,4]:
new_list.append(a[i] + a[i-1])
What it's doing is getting the current value of a
at i
and adding it a
at the previous index i-1
and appending the result to a new list.

Salaah Amin
- 382
- 3
- 14
-
1An explanation please? – PCM Sep 29 '21 at 04:03
-
I've updated the answer adding more detail. – Salaah Amin Sep 29 '21 at 08:50
-
1Thanks for you help and explanation – Nael Jn Baptiste -aka Analyze Sep 29 '21 at 14:42