'Why do I get "List index out of range" when trying to add consecutive numbers in a list using "for i in list"?

Given the following list

a = [0, 1, 2, 3]

I'd like to create a new list b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.

Like this:

b = [1, 3, 5]

(from 0+1, 1+2, and 2+3)

Here's what I've tried:

b = []
for i in a:
    b.append(a[i + 1] + a[i])

The trouble is I keep getting this error:

IndexError: list index out of range

I'm pretty sure it occurs because by the time I get the the last element of a (3), I can't add it to anything because doing so goes outside of the value of it (there is no value after 3 to add). So I need to tell the code to stop at 2 while still referring to 3 for the calculation.



Solution 1:[1]

Reduce the range of the for loop to range(len(a) - 1):

a = [0, 1, 2, 3]
b = []

for i in range(len(a) - 1):
    b.append(a[i] + a[i+1])

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

Solution 2:[2]

When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

for i in range(0, len(a)-1): Do something

Your current code won't work yet for the do something part though ;)

Solution 3:[3]

You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.

b = [i + j for i, j in zip(a, a[1:])]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkrieger1
Solution 2 Everyone_Else
Solution 3 miradulo