0

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.

1
  • So you're adding the last element in ct to... what? When i is 7 (which it will be if totrange is usually 8), ct[i+1] will be out of bounds. Commented Nov 17, 2012 at 18:19

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

Shouldn't it be "totrange should never be greater than len(ct)-1" (so that i is never greater than len(ct)-2) ?
Nope. len([0, 1]) is 2, which means that (len([0, 1]) - 1) + 1 is 2, which is an index out of range. (len([0, 1]) - 2) + 1 is 1 and will thus not be out of range.
You seem to be missing the range(totrange) part. If totrange is len(ct)-1 (i.e. 7), i greatest value will be 6, and 6+1 is a valid ct index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.