Amir
Amir

Reputation: 1428

Index out of range error in Python (IndexError: list index out of range)

I can't seem to find the issue here that I am getting out of range issue:

layerZ = [layer_1,layer_2,layer_3,layer_4,layer_5,layer_6,layer_7,layer_8,layer_9,layer_10,layer_11,layer_12,layer_13]
    for x in range(0, 12):
        layerZ_total = [np.size(layerZ[x])]
        layerZ_sp = [np.count_nonzero(layerZ[x]==0)]
        layerZ_nonSp = [np.count_nonzero(layerZ[x])]

        #Printing the results on scree to trace
        print "Layer:",x+1,"Threshhold:",repr(ths),"Total Parameters: ",layerZ_totParam[x],"# Sp: ",layerZ_sp[x],"# Remained : ",layerZ_nonSp[x],"Sp %: ",float(layerZ_sp[x])/layerZ_total[x]

Upvotes: 0

Views: 887

Answers (1)

tkhurana96
tkhurana96

Reputation: 939

This should help:

layerZ = [layer_1,layer_2,layer_3,layer_4,layer_5,layer_6,layer_7,layer_8,layer_9,layer_10,layer_11,layer_12,layer_13]

layerZ_total = []
layerZ_sp = []
layerZ_nonSp = []


for x in range(0, 12):
    layerZ_total.append(np.size(layerZ[x]))
    layerZ_sp.append(np.count_nonzero(layerZ[x]==0))
    layerZ_nonSp.append(np.count_nonzero(layerZ[x]))

    #Printing the results on scree to trace
    print "Layer:",x+1,"Threshhold:",repr(ths),"Total Parameters: ",layerZ_total[x],"# Sp: ",layerZ_sp[x],"# Remained : ",layerZ_nonSp[x],"Sp %: ",float(layerZ_sp[x])/layerZ_total[x]

In your code, the lists layerZ_total, layerZ_sp and layerZ_nonSp were reinitialized with a single value everytime inside the loop, therefore containing only one element at index 0 inside them, when you tried accessing some x index, the list index out of range error popped up.

And if you were to do processing on every layer_* of layerZ list(depending on your requirements), you need to range(0, 13) as after doing this x will take on the values 0 to 12 thereby processing every layer in your layerZ list

Upvotes: 1

Related Questions