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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
Your other option is to initialize j:
j = [None] * len(i)
Method 3
Do j.append(l) instead of j[k] = l and avoid k at all.
Method 4
You could also use a list comprehension:
j = [l for l in i]
or make a copy of it using the statement:
j = i[:]
Method 5
j.append(l)
Also avoid using lower-case “L’s” because it is easy for them to be confused with 1’s
Method 6
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]
Method 7
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}
Method 8
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
Method 9
Maybe you need extend()
i=[1,3,5,7] j=[] j.extend(i)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0