1

I know this is a rookie question but I keep getting an error I don't usually get. "Index error: List index out of range on line 12." where it says the 2 'nums'. I thought it was perfectly fine to call variables out side of a loop?

lisp = []
new = []

for x in range(1, 11):
    num = int((x * (3*x - 1))/2)
    lisp.append(num)

x = 0
y = 2

for i in lisp[1:]:
    num1 = lisp[x] + i
    num2 = lisp[y] + i
    dif1 = i - lisp[x]
    dif2 = lisp[y] - i
    smallList = [num1, num2, dif1, dif2]
    new.append(smallList)

    x += 1
    y += 1

print(new)
2
  • 2
    Have you tried doing some debugging - add some print statements immediately before the line you are getting the error, to print the list, and the index you are using into it. Commented Jun 26, 2017 at 8:53
  • I'm and egg, I forgot by the time it gets to the 10th element the list index will be out of range. Commented Jun 26, 2017 at 8:57

2 Answers 2

2

Fix using ipython.

script.py:

lisp = []
new = []

for x in range(1, 11):
    num = int((x * (3*x - 1))/2)
    lisp.append(num)

x = 0
y = 2

for i in lisp[1:]:
    num1 = lisp[x] + i
    num2 = lisp[y] + i
    dif1 = i - lisp[x]
    dif2 = lisp[y] - i
    smallList = [num1, num2, dif1, dif2]
    new.append(smallList)

    x += 1
    y += 1

print(new)

Launch ipython and do:

In [1]: run script.py
     11 for i in lisp[1:]:
     12     num1 = lisp[x] + i
---> 13     num2 = lisp[y] + i
     14     dif1 = i - lisp[x]
     15     dif2 = lisp[y] - i

IndexError: list index out of range

In [2]: y
Out[2]: 10

In [3]: len(lisp)
Out[3]: 10

Here y = 10, but len(lisp) = 10 valid index are between 0 and 9 (both inclusive, 0-based) and 10 is out of this range.

Sign up to request clarification or add additional context in comments.

Comments

0

Check and put conditions on:

x += 1
y += 1

y is going beyond the index on the line:

num2 = lisp[y] + i

Comments

Your Answer

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