Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python IndexError: list assignment index out of range

# 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

#Results in 
IndexError: list assignment index out of range
  
# You are trying to assign to j[0], which does not exist yet 
# Instead, use append:
for l in i:
    j.append(l)
    
# OR initialise j as:
j = [None] * len(i)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #python #list #assignment #index #range
ADD COMMENT
Topic
Name
6+7 =