Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of an element in array containing another element

Tags:

python

arrays

So lets say I have this array :

array = [[1,2,3],[4,5,6],[7,8,9]]

and I want to get the index of the inner array containing the 5 for example. So in this case the returned index I want is 1.

I did try ind = array.index(5) but I'm quite aware why this didnt work since the value in the brackets have to match the element in the array exactly. Another way I did this is

counter = 0
for each in array:
  if 5 in each: break
  else: counter = counter + 1

and this worked well for what I want but I wanted to check if there is an easier and cleaner way to do this. Thanks

like image 679
L.D Avatar asked Dec 08 '22 18:12

L.D


2 Answers

There is a slightly better pythonic approach using next(..). Remember that if 5 doesn't exist in any of the sub-arrays, this will throw a StopIteration. You might want to handle that.

>>> your_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> next(i for i, x in enumerate(your_list) if 5 in x)
1
like image 150
UltraInstinct Avatar answered May 19 '23 17:05

UltraInstinct


Better avoid breaks. Here is a better way:

for ind, inner_arr in enumerate(array):
    if 5 in inner_arr:
        return ind
like image 32
Jenian Avatar answered May 19 '23 17:05

Jenian