Tonikami04
Tonikami04

Reputation: 187

IndexError: list assignment index out of range in python 2.7.11

I was just solving a problem using python, and my codes are:

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

#set up initial condition
u0 = [0.0]              # Boundary conditions at t= 0
for i in range(1,N):
    u0[i] = v(x[i])

And I would want to plot the results by updating v(x) in range(0, N) after. it looks simple but perhaps you guys could help since it gives me an error, like

Traceback (most recent call last):
  File "/home/universe/Desktop/Python/sample.py", line 13, in <module>
    u0[i] = v(x[i])
IndexError: list assignment index out of range

Upvotes: 1

Views: 301

Answers (3)

user2285236
user2285236

Reputation:

Since you are using numpy, I'd suggest using np.vectorize. That way you can pass the array x directly to the function and the function will return an array of the same size with the function applied on each element of the input array.

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

vectorized_v = np.vectorize(v) #so that the function takes an array of x's and returns an array again
u0 = vectorized_v(x) 

Out:

array([  0.00000000e+00,   1.64594590e+01,   3.24699469e+01,
         4.75947393e+01,   6.14212713e+01,   7.35723911e+01,
         8.37166478e+01,   9.15773327e+01,   9.69400266e+01,
         9.96584493e+01,   9.96584493e+01,   9.69400266e+01,
         9.15773327e+01,   8.37166478e+01,   7.35723911e+01,
         6.14212713e+01,   4.75947393e+01,   3.24699469e+01,
         1.64594590e+01,   1.22464680e-14])

Upvotes: 1

C Panda
C Panda

Reputation: 3415

You could change u0[i] = v(x[i]) to u0.append(v(x[i])). But you should write more elegantly as

u0 = [v(xi) for xi in x]

Indices i are bug magnets.

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

u is a list with one element, so you can't assign values to indices that don't exist. Instead make u a dictionary

u = {}
u[0] = 0.0
for i in range(1,N):
    u[i] = v(x[i])

Upvotes: 0

Related Questions