Home > Mobile >  List indices must be not list
List indices must be not list

Time:12-17

I need to take action when pole[i][j] == 1, but it throws an error:

TypeError: list indices must be integers or slices, not list

pole = [[0,1,0],
        [1,0,1],
        [0,1,1]]
for i in pole:
    for j in pole:
        if pole[i][j] == 1:
            my_code()

CodePudding user response:

You use for i in pole which gets the actual values of pole not the indices. Here is the corrected code:

pole = [[0,1,0],
        [1,0,1],
        [0,1,1]]
for i in range(len(pole)):
    for j in range(len(pole[i])):
        if pole[i][j] == 1:
            my_code()

Alternatively, you could use the values not the indices so:

pole = [[0,1,0],
        [1,0,1],
        [0,1,1]]
for i in pole:
    for j in i:
        if j == 1:
            my_code()

CodePudding user response:

a for-in loop iterates over the elements of a list, not its indexes. Also, note you have the inner loop performing the same iteration as the outer loop, not iterating over the the sublist:

for x in pole:
    for y in x:
        if y == 1:
            my_code()

CodePudding user response:

Well,technically speaking, given that my_code() does not use i or j, you could do something like this:

for _ in range(sum(map(sum, pole))):
    my_code()

The elements in pole do not necessarily need to be 0s and 1s - you could trigger other conditions, for example:

sum(map(lambda x: sum(y > 0 for y in x), pole)
  • Related