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?
Maybe you need extend()
i=[1,3,5,7]
j=[]
j.extend(i)
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}
Do j.append(l)
instead of j[k] = l
and avoid k
at all.
You could also use a list comprehension:
j = [l for l in i]
or make a copy of it using the statement:
j = i[:]
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
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(1,20)
print(array)
# prints [1,2,20,3,4,5]
Your other option is to initialize j
:
j = [None] * len(i)
j.append(l)
Also avoid using lower-case "L's" because it is easy for them to be confused with 1's
Source: Stackoverflow.com