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?
One more way:
In this case
j
will be a numpy arrayAlso avoid using lower-case "L's" because it is easy for them to be confused with 1's
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:
Do
j.append(l)
instead ofj[k] = l
and avoidk
at all.You could use a dictionary (similar to an associative array) for j
will print :
You could also use a list comprehension:
or make a copy of it using the statement: