Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A pythonic way how to find if a value is between two values in a list

Having a sorted list and some random value, I would like to find in which range the value is.

List goes like this: [0, 5, 10, 15, 20] And value is, say 8.

The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search.

grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
    result_index += 1

print result_index

I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore. Thank you for your time!

like image 768
tm_lv Avatar asked Dec 19 '09 19:12

tm_lv


1 Answers

>>> import bisect
>>> grid = [0, 5, 10, 15, 20]
>>> value = 8
>>> bisect.bisect(grid, value)
2

Edit:

bisect — Array bisection algorithm

like image 184
Alex Brasetvik Avatar answered Oct 14 '22 07:10

Alex Brasetvik