[Tutor] IndexError: index out of bounds

Walter Prins wprins at gmail.com
Wed Mar 27 17:59:59 CET 2013


Hi Sayan,

On 27 March 2013 16:31, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:

> p_za = [None]*N is not giving away the error message.
>
> for i in range(0,N):
>     p_za.append = p_initial[i] + t*K*cos(K*p_initial[i]); is also not
> working.
>

append() is a method, so using append you want something like:

for i in range(0,N):
    p_za.append( p_initial[i] + t*K*cos(K*p_initial[i]) );

After every loop iteration, the list grows by having one item appended to
it, being the result of the expression: p_initial[i] +
t*K*cos(K*p_initial[i])


> Could you please redirect me to a link where the example is demonstrated?
>

http://courses.cms.caltech.edu/cs11/material/python/misc/python_idioms.html

See the paragraph on "Sequence multiplication".



> What is the simplest way to assign an array element a value?
>

What you have is fine for assignment to a particular slot in the list.
What you've missed and has already been pointed out, is to initialise/set
the length of your list first, before trying to set the value of arbitrary
slots.  In the C example you posted the array is declared with length 200
up front.  In your Python code however you assign [], which is a list of
length 0.   By contrast, the expression I gave you before, e.g. [None] * N,
generates a list of length N, with each element in the list being the None
object, thus initialising the list, ensuring that you can later assign to
arbitrary slots when needed.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130327/3d8a1566/attachment.html>


More information about the Tutor mailing list