Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of specific item in python matrix

I am newbie to Python programming language. And I am looking for How to get the indexes (line and column ) of specific element in matrix.

In other I way I want to do the same as this source code using lists.

myList=[1,10,54,85]
myList.index(54)

Best Regards

like image 988
Kha Lid Avatar asked Feb 04 '26 07:02

Kha Lid


2 Answers

Here's a simple function which returns the coordinates as a tuple (or None if no index is found). Note that this is for 2D matrices, and returns the first instance of the element in the matrix.

(Edit: see hiro protagonist's answer for an alternative Pythonic version)

def find(element, matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == element:
                return (i, j)

Or, if you want to find all indexes rather than just the first:

def findall(element, matrix):
    result = []
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == element:
                result.append((i, j))
    return result

You can use it like so:

A = [[5, 10],
     [15, 20],
     [25, 5]]


find(25, A) # Will return (2, 0)
find(50, A) # Will return None

findall(5, A) # Will return [(0, 0), (2, 1)]
findall(4, A) # Will return []
like image 155
FlipTack Avatar answered Feb 05 '26 22:02

FlipTack


a (in my opinion) more pythonic version of FlipTack's algorithm:

def find(element, matrix):
    for i, matrix_i in enumerate(matrix):
        for j, value in enumerate(matrix_i):
            if value == element:
                return (i, j)

in python it is often more natural to iterate over elements of lists instead of just the indices; if indices are needed as well, enumerate helps. this is also more efficient.

note: just as list.index (without a second argument) this will only find the first occurrence.

like image 34
hiro protagonist Avatar answered Feb 05 '26 21:02

hiro protagonist