I have a list:
the_list = [1, 2, 3, 4, 5]
Next I would like to sum pairs of numbers from the list, next pairs in the next step, and so on, until we get only one number at the end. The next steps would look like this:
[3, 5, 7, 9]
[8, 12, 16]
[20, 28]
[48]
I use a loop to add pairs:
the_list = [1, 2, 3, 4, 5]
for i in range(len(the_list) - 1):
a, b = the_list[i], the_list[i + 1]
c = a + b
print (c)
What gives:
3
5
7
9
But I do not know how to loop it to the next steps. Because, for now, only a very bad idea of adding to the new list comes to mind, which would be a completely wrong idea with a large starting list. How can this be done?
You can zip the list against itself offset by one index, then sum consecutive elements until the list collapses into a slngle value
l = [1, 2, 3, 4, 5]
while len(l) > 1:
l = [i+j for i,j in zip(l, l[1:])]
print(l)
Output
[3, 5, 7, 9]
[8, 12, 16]
[20, 28]
[48]
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