Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error: IndexError: list assignment index out of range [duplicate]

Tags:

python

a=[]
a.append(3)
a.append(7)

for j in range(2,23480):
    a[j]=a[j-2]+(j+2)*(j+3)/2

When I write this code, it gives an error like this:

Traceback (most recent call last):
  File "C:/Python26/tcount2.py", line 6, in <module>
    a[j]=a[j-2]+(j+2)*(j+3)/2
IndexError: list assignment index out of range

May I know why and how to debug it?

like image 341
Hick Avatar asked Mar 10 '26 15:03

Hick


2 Answers

Change this line of code:

a[j]=a[j-2]+(j+2)*(j+3)/2

to this:

a.append(a[j-2] + (j+2)*(j+3)/2)
like image 89
hao Avatar answered Mar 12 '26 06:03

hao


You're adding new elements, elements that do not exist yet. Hence you need to use append: since the items do not exist yet, you cannot reference them by index. Overview of operations on mutable sequence types.

for j in range(2, 23480):
    a.append(a[j - 2] + (j + 2) * (j + 3) / 2)
like image 40
Stephan202 Avatar answered Mar 12 '26 05:03

Stephan202



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!