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]

gariepy
  • 3,576
  • 6
  • 21
  • 34
Jenny
  • 1

2 Answers2

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)
darkryder
  • 792
  • 1
  • 8
  • 25
  • 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 – Jenny Aug 27 '15 at 07:32
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
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29