Liondancer
Liondancer

Reputation: 16489

IndexError: list assignment index out of range for arrays

I am new to python. I think n begins at 0 and it will increase up till the last element on stack1.

arraylength = 3*stack1length
array = [0]*arraylength
for n in stack1:
    array[3*n] = stack1[n]

my array length is 3 times the length of stack1

Upvotes: 0

Views: 1007

Answers (1)

Veedrac
Veedrac

Reputation: 60227

for n in stack1:

Goes through the items in stack1.

You seem to be wanting to go through the indexes:

for n in range(len(stack1)):
    array[3*n] = stack1[n]

Note that this is better written with the convenience function, enumerate,

for n, stack1_n in enumerate(stack1):
    array[3*n] = stack1_n

Additionally, you can use some evil hackz:

array[::3] = stack1

array[::3] is every third item in array (start:stop:step), and therefore you're setting every third item to the corresponding item in stack1.

Upvotes: 9

Related Questions