user1724602
user1724602

Reputation: 27

Index Error when adding two items in a list

So, I have 8 randomly generated numbers, all referenced with ct[i]. I want to add a number (ct[i]) with the one referenced by ct[i+1]. However, this produces a list index out of range error. What's wrong?

for i in range(totrange):
    tot1 = ct[i] + ct[i+1]

totrange is usually 8, but I wanted to have a bit of flexibility.

Upvotes: 0

Views: 75

Answers (2)

David Pärsson
David Pärsson

Reputation: 6257

If totrange is 8 and ct contains 8 elements, the last ct[i+1] call will try to get the 9th element from ct, causing a list index out of range error.

Because of this, totrange should never be greater than len(ct) - 1.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

You should probably use range(len(ct)-1) to handle this issue, as for the last i, i+1 is a value which is greater than the last index of ct.

examples:

In [30]: ct=range(5)     #ct =[0,1,2,3,4]

In [31]: for i in range(len(ct)-1):
    print(ct[i]+ct[i+1])
   ....:     
1
3
5
7

or better use a zip() based solution, no need of using indexes at all:

In [32]: for x,y in zip(ct,ct[1:]):
    print (x+y)
   ....:     
1
3
5
7

Upvotes: 2

Related Questions