Reputation:
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)
Upvotes: 1
Views: 81
Reputation: 144
Check and put conditions on:
x += 1
y += 1
y
is going beyond the index on the line:
num2 = lisp[y] + i
Upvotes: 0
Reputation: 3603
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.
Upvotes: 2