2

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
  • I'm impressed you didn't get an error on array[(1, 2, 3)] or the lack of zeros being imported... - are you copying/pasting code, or typing it in? Commented Nov 19, 2013 at 13:11
  • Typing it in, it was done correctly in the console, sorry about that! Commented Nov 19, 2013 at 13:14

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

I think I see, so even though Python indexes start with 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?
@user3008862 It starts with i=1 because 1 is the 0-th element of the array. I expanded the answer a bit to make it clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.