Home > Software design >  Code does not return the right index value while checking list in a list
Code does not return the right index value while checking list in a list

Time:12-22

I am checking the letter B in a 2D list but it does not working right.

table1=[[ ' - ', ' B ', ' C ',], 
        [ ' B ', ' - ', ' C '], 
        [ ' B ', ' B ', ' C '], 
        [ ' B ', ' - ', ' C ']]
for element in table1:
    for index in range(len(element)):
        if element[index] == " B ":
            print(table1.index(element),index)

I expect to get output like 0 1, 1 0, 2 1, 3 0 But instead o get 0 1, 1 0, 2 1, 1 0 Where do I make the mistake? It works correctly until the last B, could this problem happen because of that?

CodePudding user response:

The index() method on a list returns the first index of the first occurrence of the element. Since your first and last rows are same, it returns as soon as it encounters the first row since it matches the condition it is checking for. A better way to achieve the desired result would be to use the enumerate() function which adds a counter to the iterable and returns it. You can modify the code as follows:

table1=[[ ' - ', ' B ', ' C ',], 
        [ ' B ', ' - ', ' C '], 
        [ ' B ', ' B ', ' C '], 
        [ ' B ', ' - ', ' C ']]

for rowIndex, element in enumerate(table1):
    for colIndex, nestedElement in enumerate(element):
        if nestedElement == " B ":
            print(rowIndex,colIndex)

You can run this code online here.

CodePudding user response:

What you could do is:

for i in range(len(table1)):
    for j in range(len(table1[i])):
        if (table1[i][j] == ' B '):
            print("({0}, {1})".format(i,j))

The outer loop will iterate from 0 to the length of table1, meaning the amount of rows. So i will represent the current row. The inner loop will iterate from 0 to the length of each row, so j will represent the current column.

  • Related