using .index(" ") for nested list in python

Question:

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
Asked By: guinab

||

Answers:

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.

Answered By: Tomer Ariel

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
Answered By: 0xRyN
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.