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.

3
  • Does this answer your question? How to find the index of a value in 2d array in Python? Commented Apr 22, 2021 at 8: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? Commented Apr 22, 2021 at 8:58
  • I expect the output to be [0][1] for yam Commented Apr 22, 2021 at 9:01

4 Answers 4

3

u may use this answer

c="yam"
index=[(i, fruits.index(c)) for i, fruits in enumerate(array) if c in fruits]
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

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!
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)]

2 Comments

Is there another way without using numpy?
I don't know. Only if you do a manual search... for in for
0

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.