1

Assuming I want to use the position of an element in a 2d list knowing the element itself, what would be the command to find the index? For a simple list the method list.index(element) works, for example:

    my_list = ["banana", "yam", "mango", "apple"]
    print(my_list.index("yam")
    >> 1
    print(my_list[my_list.index("yam")])
    >> yam

But the same method doesn't work for 2d arrays. For example:

    array = [["banana", "yam"],["mango", "apple"]]
    print(array.index("yam"))

I get a ValueError: 'yam' is not in list.

Mady Daby
  • 1,271
  • 6
  • 18
Supernyv
  • 33
  • 9
  • Does this answer your question? [How to find the index of a value in 2d array in Python?](https://stackoverflow.com/questions/27175400/how-to-find-the-index-of-a-value-in-2d-array-in-python) – Mady Daby Apr 22 '21 at 08:52
  • That is not a "2D array". That is just a list with other list objects in it. In any case, what value to do *expect*? – juanpa.arrivillaga Apr 22 '21 at 08:58
  • I expect the output to be [0][1] for yam – Supernyv Apr 22 '21 at 09:01

4 Answers4

3

u may use this answer

c="yam"
index=[(i, fruits.index(c)) for i, fruits in enumerate(array) if c in fruits]
Sîd Âlï
  • 65
  • 2
  • 3
1

this is my code

array = [["banana", "yam"],["mango", "apple"]]
for i,j  in enumerate(array):
     if "yam" in j:
         index=(i,j.index("yam"))
         break
print(index)
Sîd Âlï
  • 65
  • 2
  • 3
  • Thanks. So there really is no simpler way. I intend to use the found index just like I would for a simple list (for example to replace the element in that index by another one). I guess this is okay , thanks! – Supernyv Apr 22 '21 at 09:19
0

What you can do is use np.where in the following way:

a = np.array([["banana", "yam"],["mango", "apple"]])
list(zip(*np.where(a == "yam")))
>> [(0, 1)]
Octav
  • 443
  • 3
  • 9
0

This worked fine. I wrote a function to return the index for any given element in the array!

enter image description here

Supernyv
  • 33
  • 9