[Tutor] IndexError: index out of bounds

Peter Otten __peter__ at web.de
Wed Mar 27 18:13:30 CET 2013


Sayan Chatterjee wrote:

> When trying to print or assign array elements, getting the following
> error:
> 
> Traceback (most recent call last):
>   File "ZA.py", line 32, in <module>
>     p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]);
> IndexError: index out of bounds
> 
> I am using Numpy, is it due to that? I am attaching the code herewith.

If you are using numpy it is likely that you don't need to loop over the 
index explicitly. Assuming t and K are scalars, and p_initial is a numpy 
array you can write

p_za = p_initial + t * K * numpy.cos(K*p_initial)

For example:

>>> import numpy
>>> p_initial = numpy.array([1.2, 3.4, 5.6])
>>> t = 1.1
>>> K = 2.2
>>> p_initial + t*K*numpy.cos(K*p_initial)
array([-0.92189929,  4.28408588,  7.94692559])

Quite powerful, once you get the knack of it.



More information about the Tutor mailing list