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

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?

This question is related to python list exception

The answer is


Maybe you need extend()

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

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}

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[:]

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


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(1,20)

print(array)

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

Your other option is to initialize j:

j = [None] * len(i)

j.append(l)

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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback