Search code examples
listnumpytypeerrorlis

while executing loop the error is list indices must be intergers,not tuple


I want to store all the iteration output in a matrix(of size 200x200). While executing the code : got the error at the

for t in (T2/Taw)*np.arange(-Taw,Taw-1):
    i=i+1;
    j=0;
    for Fd in (B/Taw)*np.arange(-Taw,Taw-1):
        j=j+1;
        val1=1-abs(t)/T2;
        val2=pi*T2*val1;
        val3=Fd+mu*t+np.spacing(1);
        val4=val2*val3;
        ambg[j,i]=np.abs(val1*(sin(val4)/(val4)))**2;


---> 62         ambg[j,i]=np.abs(val1*(sin(val4)/(val4)))**2;

              TypeError: list indices must be integers, not tuple

Solution

  • ambg=[] is a list. It can only be indexed with an integer, e.g ambg[i]. ambg[i,j] is the equivalent to ambg[(i,j)], where (i,j) is a tuple. Hence the error message.

    If ambg was a list of lists, then it could indexed as ambg[i],[j]. But lists of lists are often constructed by iteratively appending values to a list(s).

    If you initialized ambg=np.zeros((N,M)) where i and j will range over range(N) and range(M), then your code should work.

    However initializing a numpy array element by element like this is slow, and considered poor practice. I haven't studied your code in detail, but it looks like you might be able to construct ambg with vector operations using T = (T2/Taw)*np.arange(-Taw,Taw-1) and FD = (B/Taw)*np.arange(-Taw,Taw-1).

    For example T[:,None] is a single column array, and FD[None,:] a single row array, that together can be used to calculate the NxN array based on all combinations of their values.

    Experiment with something simpler like I = np.arange(10) and J = np.arange(10), and look at I[:,None]*J[None,:], or their sum, or difference, etc.