The index method will raise in a ValueError if the element is not found in the list. This is why the first iteration throws an exception.
You can either catch the error or check if the element is in the list before using the index method.
Here's an example:
a = [[1,2,3],[4,5,6],[7,8,9]]
def find_index(list_of_lists, item):
for sublist in list_of_lists:
try:
return sublist.index(item)
except ValueError:
continue
print(find_index(a, 4))
Which yields 0 as expected.
Alternatively, you could implement a look-before-you-leap approach and check if the element exists in the list before attempting to use the index method. This is less efficient however, because checking if an element exists in a list is a linear time operation.
def find_index(list_of_lists, item):
for sublist in list_of_lists:
if item in sublist:
return sublist.index(item)
This is less efficient and less "pythonic", but still viable.