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:15

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array

查看更多
余欢
3楼-- · 2019-01-01 15:16
j.append(l)

Also avoid using lower-case "L's" because it is easy for them to be confused with 1's

查看更多
流年柔荑漫光年
4楼-- · 2019-01-01 15:18

j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
    j.append(l)
查看更多
爱死公子算了
5楼-- · 2019-01-01 15:19

Do j.append(l) instead of j[k] = l and avoid k at all.

查看更多
不流泪的眼
6楼-- · 2019-01-01 15:19

You could use a dictionary (similar to an associative array) for j

i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0

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

print j

will print :

{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
查看更多
梦该遗忘
7楼-- · 2019-01-01 15:21

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]
查看更多
登录 后发表回答