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

PythonListException

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Your other option is to initialize j:

j = [None] * len(i)

Solution 3 - Python

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

Solution 4 - Python

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]

Solution 5 - Python

j.append(l)

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

Solution 6 - Python

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]

Solution 7 - Python

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}

Solution 8 - Python

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

Solution 9 - Python

Maybe you need extend()

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVladanView Question on Stackoverflow
Solution 1 - PythonSteve MayneView Answer on Stackoverflow
Solution 2 - PythonRshView Answer on Stackoverflow
Solution 3 - PythonkhachikView Answer on Stackoverflow
Solution 4 - PythonJason SundramView Answer on Stackoverflow
Solution 5 - PythonTomView Answer on Stackoverflow
Solution 6 - PythonMehmet Kagan KayaalpView Answer on Stackoverflow
Solution 7 - PythonCedricView Answer on Stackoverflow
Solution 8 - PythonAlexView Answer on Stackoverflow
Solution 9 - PythonFred MooView Answer on Stackoverflow