开发者

Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?

开发者 https://www.devze.com 2023-02-25 13:03 出处:网络
I tried writing some code like: i = [1, 2, 3, 5, 8, 13] j = [] k = 0 for l in i: j[k] = l k += 1 But I get an er开发者_JS百科ror message that says IndexError: list assignment index out of range, ref

I tried writing some code like:

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

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

But I get an er开发者_JS百科ror message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?


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.


Your other option is to initialize j:

j = [None] * len(i)


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


You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]


j.append(l)

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


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

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)

print(array)

# prints [1,20,2,3,4,5]


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}


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


Maybe you need extend()

i=[1,3,5,7]
j=[]
j.extend(i)
0

精彩评论

暂无评论...
验证码 换一张
取 消