Python Loop: List Index Out of Range

+1 vote
1 view
in Python

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 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])

b

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 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.

by (68.3k points)
edited by

To get rid of this error you can try reducing the range of the for loop to range(len(a)-1) see the code below:-

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

for i in range(len(a)-1):

b.append(a[i]+a[i+1])

print(b)

You can also write it as a list comprehension:-

b = [a[i] + a[i+1]

for i in range(len(a)-1)]:

print(b)

To know more about this you can have a look at the following video tutorial:-

by (210 points)

We can also use while loop to get the same answer, but in while loop we can use break and continue statements if the length of the list is too long and we want to control the list elements, i.e, we can neglect or reject the non numerical list elements in exists in the project.

# Here is the Code:(But I've not included the break or continue statements as of now)

a = [0, 1, 2, 3]

i = 0

b = []

while i < (len(a) - 1):

b.append(a[i] + a[i + 1])

i = i + 1

print(b)