JavaGelp
JavaGelp

Reputation: 3

How to print the sum of the current and previous element in a list

I am trying to iterate through a list of numbers and print the sum of the current element and the previous element using python. For example,

Given numbers = [5,10,15,20,25,30,30], the output should be 5, 15, 25, 35, 45, 55, 60,. This is the following code that I have tried, it is very close to the answer but the first element is wrong.

numbers = [5, 10, 15, 20, 25, 30, 30]

i = 0
for x in range(1, 8):
    print(numbers[i] + numbers[i - 1], end=", ")
    i += 1

I am getting the output 35, 15, 25, 35, 45, 55, 60,. What am I doing wrong?

Upvotes: 0

Views: 9118

Answers (6)

blhsing
blhsing

Reputation: 106445

You can pair adjacent items of numbers by zipping it with itself but padding one with a 0, so that you can iterate through the pairs to output the sums in a list comprehension:

[a + b for a, b in zip([0] + numbers, numbers)]

or by mapping the pairs to the sum function:

list(map(sum, zip([0] + numbers, numbers)))

Both would return:

[5, 15, 25, 35, 45, 55, 60]

Upvotes: 7

Jongware
Jongware

Reputation: 22447

Cheat, and add a [0] at the start to prevent the first sum to be wrong. You'll run into problems at the end, though, because then the list in the enumerate is one item longer than the original, so also clip off its last number:

print ([a+numbers[index] for index,a in enumerate([0]+numbers[:-1])])

Result:

[5, 15, 25, 35, 45, 55, 60]

If you want to see how it works, print the original numbers before addition:

>>> print ([(a,numbers[index]) for index,a in enumerate([0]+numbers[:-1])])
[(0, 5), (5, 10), (10, 15), (15, 20), (20, 25), (25, 30), (30, 30)]

The enumerate loops over the changed list [0, 5, 15, .. 55], where everything is shifted up a place, but numbers[index] still returns the correct index from the original list. Adding them up yields the correct result.

Upvotes: 0

marcos
marcos

Reputation: 4510

This list comprehension works:

numbers = [5, 10, 15, 20, 25, 30, 30]

output = [value + numbers[i-1] if i else value for i, value in enumerate(numbers)]
print(output)

>>> [5, 15, 25, 35, 45, 55, 60]

Upvotes: 0

aminrd
aminrd

Reputation: 4980

This should work:

numbers = [5, 10, 15, 20, 25, 30, 30]

output = [numbers[i]+numbers[i-1] if i > 0 else numbers[i] for i in range(len(numbers))]
print(output)

Upvotes: 1

Borja
Borja

Reputation: 99

You are starting at i = 0, so the first number you are adding is the 0 and the -1 (the last one, in this case). That's why you are getting the 35 (5+30).

Upvotes: 0

felipe
felipe

Reputation: 8025

You are starting at index 0, where it seems your intended output starts at index 1:

Here is a better solution:

numbers = [5, 10, 15, 20, 25, 30, 30]

for i in range(len(numbers)):
    if i == 0:
        print(numbers[i])
    else:
        print(numbers[i - 1] + numbers[i])

Outputs:

5
15
25
35
45
55
60

Upvotes: 2

Related Questions