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
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
Better avoid break
s. Here is a better way:
for ind, inner_arr in enumerate(array):
if 5 in inner_arr:
return ind
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With