IndexError: list assignment index out of range

2019-01-01 14:55发布

Please consider the following code:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

for l in i:
    j[k] = l
    k += 1

print j

The output (Python 2.6.6 on Win 7 32-bit) is:

> Traceback (most recent call last): 
>     j[k] = l IndexError: list assignment index out of range

I guess it's something simple I don't understand. Can someone clear it up?

8条回答
牵手、夕阳
2楼-- · 2019-01-01 15:24

I think the Python method insert is what you're looking for:

Inserts element x at position i.

array = [1,2,3,4,5]

array.insert(1,2)

print(array)

# prints [1,2,2,3,4,5]
查看更多
冷夜・残月
3楼-- · 2019-01-01 15:39

Your other option is to initialize j:

j = [None]*max(i)
查看更多
登录 后发表回答