2

I want to get the index of the "4" in the nested list, it is working cause I suppress the error. any idea for a alternative?

a = [[1,2,3],[4,5,6],[7,8,9]]

for i in range(len(a)):
    try:
        index = a[i].index(4)
        print(i, index)  
    except:
        pass
2
  • There are lots of alternatives, but no clear reason for suggesting any particular one over what you currently have. Commented Sep 3, 2022 at 20:21
  • This sounds more like a question for codereview.stackexchange.com. Commented Sep 3, 2022 at 20:21

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not necessarily much less efficient to look before you leap. list.index is a linear time operation too, the only difference is that it raises an exception if it reaches the end of the list before finding a match.
The asymptotic time complexity is the same, but using the in operator kind of doubles it needlessly.
2

This is code that won't throw an error and doesn't use index() function.

for i in range(len(a)):
    for j in range(len(a[i])):
        if a[i][j] == 4:
            print("Found at", i, j)
            break

2 Comments

Well done because a[1][0] returns the 4 that was searched in the first place.
why are you using range? it's much better to use the iterable itself, if you need the index too, use enumerate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.