Why does this iterative list-growing code give IndexError: list assignment index out of range?

后端 未结 9 1822
慢半拍i
慢半拍i 2020-11-22 07:34

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

9条回答
  •  孤街浪徒
    2020-11-22 08:17

    You could also use a list comprehension:

    j = [l for l in i]
    

    or make a copy of it using the statement:

    j = i[:]
    

提交回复
热议问题