Explore Courses Blog Tutorials Interview Questions
+1 vote
in Python by (47.6k points)

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


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.

2 Answers

0 votes
by (106k 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): 



You can also write it as a list comprehension:-

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

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


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

To Learn what is python and python applications then visit this Data Science with Python Course.

You can refer to our Python online course for more information.

0 votes
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


Related questions

0 votes
2 answers
asked Aug 30, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 25, 2019 in Python by Eresh Kumar (45.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)

Browse Categories