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

0 votes

Given the following list

a = [0, 1, 2, 3]

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

Like this:

b = [1, 3, 5]

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

Can somone help me with this?

Apr 24, 2022 in Python by Kichu
• 19,040 points
723 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

The problem in your for loop is that:

  • In your for loop, you're iterating through the elements of a list a. You used the items in the list to index in the body of the loop. fix this issue by iterating over a range of indexes instead:    
     for i in range(len(a))
  • The next issue is that if you're indexing not only a[i] but also a[i+1], you'll get an IndexError. To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.


I hope this helps you.

answered Apr 25, 2022 by narikkadan
• 63,600 points

edited Mar 5

Related Questions In Python

+1 vote
1 answer
0 votes
0 answers
0 votes
1 answer

Python: Sort list of lists numerically

You can try and De-dupe it with ...READ MORE

answered May 20, 2019 in Python by SDeb
• 13,300 points
2,340 views
0 votes
0 answers

How to return dictionary keys as a list in Python?

Now, in Python >= 3.3, I get something ...READ MORE

Feb 18, 2022 in Python by Dev
• 6,000 points
498 views
0 votes
0 answers

Double the value of array on a match - Python

I want to iterate through the elements ...READ MORE

Apr 24, 2022 in Python by Kichu
• 19,040 points
1,949 views
0 votes
1 answer

Crawling after login in Python

You missed a few login data forms, ...READ MORE

answered Sep 7, 2018 in Python by Priyaj
• 58,020 points
1,788 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP