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 []
Answer from FlipTack on Stack OverflowHere'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 []
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.
Let's say I have a matrix that looks like this :
[[1,2,3],[4,5,6],[7,8,9]]
and I want to find out the index from some specific number, like 4. I know there is the index method for lists - is there nothing similar for a 2D matrix? If no, is there a different simple way to find it?
python - Find indices of a value in 2d matrix - Stack Overflow
python - Return index of element in matrix - Stack Overflow
python - How can I get the index of an element from a loop, sourced from a numpy array? - Stack Overflow
python - How can I get the index of an element in a matrix from a list that is generated from that matrix? - Stack Overflow
If you convert mymatrix to a numpy array you can jsut use numpy.where to return the indices:
>>> import numpy as np
>>> mymatrix=[[1,2,3],[4,5,6],[7,8,9]]
>>> a = np.array(mymatrix)
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> b = np.where(a==9)
>>> b
(array([2]), array([2]))
>>> mymatrix=[[1,2,3],[9,5,6],[7,8,9]]
>>> a = np.array(mymatrix)
>>> a
array([[1, 2, 3],
[9, 5, 6],
[7, 8, 9]])
>>> b = np.where(a==9)
>>> b
(array([1, 2]), array([0, 2]))
If you want all of the locations that the value appears at, you can use the following list comprehension with val set to whatever you're searching for
[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
for example:
>>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
>>> val = 9
>>> [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
[(0, 2), (1, 1), (2, 2)]
EDIT
It's not really true that this gets all occurrences, it will only get the first occurrence of the value in a given row.
First, .append() with 2 arguments isn't going to work. You probably meant to append a tuple or list consisting of ri and ei.
Also, please don't use built–in names like list for variables – that's confusing for everyone, including the interpreter.
And as for solving your problem in an efficient manner, it would be best to iterate over list (here values_sought) not in the outer–, but in the innermost loop, so as to avoid pointless checking of the same matrix coordinates multiple times, like this:
values_sought = [1, 2, 3]
matrix = [[0,1,2], [3,2,0], [1,2,3]]
coordinates = []
for row_index, row in enumerate(matrix):
if not values_sought: break
for column_index, value_present in enumerate(row):
if not values_sought: break
for value_sought_index, value_sought in enumerate(values_sought):
if value_present == value_sought:
coordinates.append((row_index, column_index))
values_sought.pop(value_sought_index)
break
Values are removed from values_sought after being found, so you may want to have a temporary list for that purpose if you need to still have these values afterwards.
There are 2 solutions:
- Use two
breakkeywords as in @Vilius Klakauskas response. Here you can read more about usingelsewithforandbreakstatements.
or
- Declare a function with
returnas below:
def find(i):
for ri, row in enumerate(matrix):
for ei, elem in enumerate(row):
if i == matrix[ri][ei]:
return (ri, ei)
and call it in a loop:
coordinates = []
for i in list:
coordinates.append(find(i))
coordinates output:
[(0, 1), (0, 2), (1, 0)]