Find the minimum and maximum indices of a list given a condition
Filter the zipped list with its indixes and take the min and the max:
>>> list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
>>> filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
>>> max(filtered_lst)
(7, 1.0)
>>> min(filtered_lst)
(3, 1.0)
If you just need the index, unpack the returned value:
>>> maX,_ = max(filtered_lst)
>>> maX
7
An alternative would be to use next()
:
list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
print(next(idx for idx, item in enumerate(list_A) if item>0))
print(next(len(list_A)-1-idx for idx, item in enumerate(list_A[::-1]) if item>0))
Output
3
7
Using next()
to find the first item in the list > 0
is an elegant solution.
To find the last item in the list > 0
is trickier with this method. I use next()
to iterate over and find the first item > 0
in the reversed list using list_A[::-1]
. I then convert the index generated to the correct index by subtracting it from len(list)-1
, using len(list)-1-idx
.