Q:

Mysterious IndexError - very basic issue (Python)

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?

A:

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

