I'm having a problem with a bit of code, I feel like I must be missing something fundamental here. A simple example that gives the same error as I am having is as follows:
from numpy import array,zeros
x = array([1,2,3])
f = zeros(len(x))
for i in x:
f[i] = x[i] + 1
And the traceback reads as follows:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
C:\WINDOWS\system32\<ipython-input-5-6b6b88f30156> in <module>()
1 for i in x:
----> 2 f[i] = x[i] + 1
3
IndexError: index out of bounds
This has been puzzling me for far too long, but I just can't seem to see what the problem is here? Could someone lend a hand?
2 Answers 2
In this loop:
for i in x:
f[i] = x[i] + 1
i takes the values 1, 2 and then 3. x[i] is not what you think it is. i already contains the content of a cell of the array x. Since the indexes of the array start from 0, you do an IndexError when trying to get the element of index 3 (which would be the 4th element).
You probably wanted something such as:
for i in range(len(x)):
f[i] = x[i] + 1
That could also be written:
for i, v in enumerate(x):
f[i] = v + 1
Comments
When you do for i in some_list, i refers to elements of that list, rather than their indexes. For example:
In [1]: for i in [3, 2, 1]:
...: print i
...:
3
2
1
However, you then use i as an index.
You iterate with i over x, and thus i takes values of 1, 2 and 3. But 3 is a too big index for an array of length 3. The last index is 2, as in Python indexes start with 0.
2 Comments
0 the for loop starts at i=1? In that case, adding an extra element to f should fix my problem, but that doesn't seem like a particularly elegant solution?i=1 because 1 is the 0-th element of the array. I expanded the answer a bit to make it clearer.
array[(1, 2, 3)]or the lack ofzerosbeing imported... - are you copying/pasting code, or typing it in?