Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return first index value of list above threshold

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading