-1

Looking to find the element index of an element in a nested loop.

table = [
    [1, "Y", 3],
    [4, 5, "K"]
]      
for i in range(len(table[0])):
    for j in range(len(table)):
        print(table[i].index("Y"))`

But every time I run the the code it tells me Y is not in my list

Prune
  • 76,765
  • 14
  • 60
  • 81

2 Answers2

3

You don't need the nested loop. You can loop through the rows and call index() on the row. You can catch the error that will happen when Y is not in the list. This is a Python style of asking forgiveness instead of permission:

for row in table:
    try:
        print(row.index("Y"))
    except ValueError:
        pass

If you just want to know if 'Y' is in the table you can use any():

any('Y' in row for row in table)
# True
Mark
  • 90,562
  • 7
  • 108
  • 148
1

Your inner loop doesn't make any sense; index already covers the entire list; why do you need to do that 3 times?

You will get an error if the item doesn't appear. Instead

for i in range(len(table)):
    if 'Y' in table[i]:
        print(i, table[i].index('Y'))

For each row, you check whether Y appears. If it does, then you print the row and column number where it appears.

Prune
  • 76,765
  • 14
  • 60
  • 81