Python – searching an item in a multidimensional array in python

findmultidimensional-arraypythonsearch

i have this multidimensional array in python.

hello = [(['b', 'y', 'e'], 3), (['h', 'e', 'l', 'l', 'o'], 5), (['w', 'o', 'r', 'l', 'd'], 5)]

and I wanted to find the index of number 3, I tried using hello.index(3) but won't work. Any solutions?

Best Answer

>>> [x[0] for x in hello if x[1] == 3][0]
['b', 'y', 'e']

if you need index of item, try

>>> [i for i, x in enumerate(hello) if x[1] == 3][0]
0

for multiple results just remove [0] at the end:

>>> hello.append((list("spam"), 3))
>>> hello
[(['b', 'y', 'e'], 3), (['h', 'e', 'l', 'l', 'o'], 5), (['w', 'o', 'r', 'l', 'd'], 5), (['s', 'p', 'a', 'm'], 3)]
>>> [x[0] for x in hello if x[1] == 3]
[['b', 'y', 'e'], ['s', 'p', 'a', 'm']]
>>> [i for i, x in enumerate(hello) if x[1] == 3]
[0, 3]
>>>