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

后端 未结 9 1816
慢半拍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:00

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

    0 讨论(0)
  • 2020-11-22 08:02
    j.append(l)
    

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

    0 讨论(0)
  • 2020-11-22 08:06

    Maybe you need extend()

    i=[1,3,5,7]
    j=[]
    j.extend(i)
    
    0 讨论(0)
  • Your other option is to initialize j:

    j = [None] * len(i)
    
    0 讨论(0)
  • 2020-11-22 08:11

    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)
    

    Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:

    j = list(i)
    

    Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

    i = [1, 2, 3, 5, 8, 13]
    j = [None] * len(i)
    #j == [None, None, None, None, None, None]
    k = 0
    
    for l in i:
       j[k] = l
       k += 1
    

    The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.

    0 讨论(0)
  • 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[:]
    
    0 讨论(0)
提交回复
热议问题