I have a sorted list of values and I would like to return the index of the first value above a threshold. Is there a more pythonic way to return this value instead of looping thru and checking each item?
demo_list = [1,1,3,5,8,13]
threshold = 4
## Some Magic Non-for-loop code here
## Returns 3
## demo_list[3] == 5
>Solution :
Not as optimal as a binary search, but you can do it in one fairly graceful line using a generator expression:
>>> demo_list = [1,1,3,5,8,13]
>>> threshold = 4
>>> next(i for i, v in enumerate(demo_list) if v > threshold)
3
Binary search is a little trickier, but more efficient if the list is very large:
>>> def first_over_ind(a, t, i=0) -> int:
... if a[0] > t:
... return i
... mid = len(a) // 2
... if a[mid] > t:
... if a[mid-1] <= t:
... return i + mid
... return first_over_ind(a[:mid], t, i)
... return first_over_ind(a[mid:], t, i + mid)
...
>>> first_over_ind(demo_list, threshold)
3