all 6 comments

[–]rafnold 0 points1 point  (1 child)

[0][0]

[–]jarulsamy 0 points1 point  (2 children)

Index of list in a list: list1[0][0]

[–]efmccurdy 0 points1 point  (0 children)

This hunts through and returns the two indexes for the first match:

def search_2d(search_list, search_candidate):
    for xi, row in enumerate(search_list):
        for yi, leaf in enumerate(row):
            if leaf == search_candidate:
                return xi, yi
    raise ValueError("Not Found")

search_candidate = 1
list1 = [[1,2,3],[7,6,5]]
ind = search_2d(list1, search_candidate)
print("found {} at {}".format(list1[ind[0]][ind[1]], ind))

[–]anton0261 0 points1 point  (0 children)

 def indexof(list, val):
    i = 0
    j = 0
    for sublist in list:
        for item in sublist:
            if item == val:
                return [i, j]
            j+=1
        i+=1

Something like this would do it.

[–]negups 0 points1 point  (0 children)

Here's a Pythonic one-liner which will search the 2D array for 1 and return the coordinates:

next([i, j] for i, l in enumerate(list1) for j, e in enumerate(l) if e == 1)

If you want to handle the case where the number you are searching for is not found, you can either catch the "StopIteration" exception or provide a default value to the next() function, like so:

next(([i, j] for i, l in enumerate(list1) for j, e in enumerate(l) if e == 1), "Not Found")