Search code examples
pythonindexingindices

Set negative indices in list to zero


The following function is placed in a for loop, where because of the for loop indices can get high negative values as in the following example:

C_ki[2][1] = max (C_ki[1][1], C_ki[3][-7] , C_ki[2][0])

# C_ki is defined as:

C_ki = [[0]*(7) for x in range(3)]

C_ik = [[0]*(3) for x in range(7)]

For calculating the above C_ki[2][1], python gives an error list index out of range because of the negative index. Is there a manner to set C_ki[3][-7] to zero for negative indices or do not take it into account for the max function?


Solution

  • So, if i is your (possibly) negative index you can simply do something like this

    C_ki[2][1] = max (C_ki[1][1], C_ki[3][max(i,0)] , C_ki[2][0])
    

    If, as I suspect, you want the whole element value set to zero than you can use a conditional statement

    C_ki[2][1] = max (C_ki[1][1], 0 if i <0 else C_ki[3][i] , C_ki[2][0])