Alexis
Alexis

Reputation: 2294

An efficient way to grab the indexes for a two dimension list in python

I have this list:

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

And I want the index for, let's say number nine. It would be (2,2). I want an efficient and less verbose way to get the x,y indexes and I tried this:

def my_indexes(the_list):
    (i_s, j_s) = [[(i, j) for j, cell in enumerate(row) if cell == 9] for i, row in enumerate(the_list) if 9 in row][0][0]
    return (i_s, j_s)

my_indexes(my_list)
(2, 2)

It works but perhaps my approach is overcomplicated. Please, could you help me with a better approach? Thank you.

Upvotes: 0

Views: 65

Answers (2)

Jonath Sujan
Jonath Sujan

Reputation: 103

You can try to use this.

n = 9
[(i, sub_list.index(n)) for i, sub_list in enumerate(my_list) if n in sub_list]

I got the output as [(2,2)] for your input.

This returns a list of tuples with indexes of all occurrences. If you need only the first occurrence you can break the iteration on the first encounter. I couldn't think of a much simpler one

Upvotes: 1

David Kaftan
David Kaftan

Reputation: 2174

Since this is tagged numpy, I'll give you the numpy solution

np_list = np.array(my_list)                                                                                         
np.argwhere(np_list == 9)

array([[2, 2]], dtype=int64)  

Upvotes: 1

Related Questions