0

I am having a 2D array.

grid[0][0]= hat
grid[0][1]= cat
grid[1][1]= bat

Now, if I have the value cat, could I retrieve those index i.e [0][1]

2
  • Are you looking for something to search for a specific value's position in the array? Commented Aug 26, 2015 at 7:33
  • @Jenny If you like my answer, you should accept this. Just click left side and accept. you will also get some point Commented Aug 26, 2015 at 7:45

2 Answers 2

1

You could iterate over all the elements like this:

def find(needle, hay):
  for x in hay:
    for y in x:
      if hay[x][y] == needle: return x, y
  return -1, -1

And then use this function

find('cat', grid)
Sign up to request clarification or add additional context in comments.

1 Comment

I am declaring my multidimensional array this way grid=[[0 for x in range(5)] for x in range(5)] On calling find() it is throwing this error: TypeError: list indices must be integers, not list
1

Yes. you can do by

for i in grid:
    for j in i:
        if grid[i][j] == 'cat':
            print i, j

Output:

0 1

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.