2

What's the easiest way to check weather an object is in a sorted list? I have found bisect, but that only finds the insertion points. Sure this index could then be used to check if the object exists in the list. But is there a easier way?

Something similar to the "in" command? Returning a True/False but for sorted lists?

4
  • 3
    Think about it, if bisect lets you find the insertion point, how you could check if the value is in the list at that point.. Commented Feb 5, 2018 at 16:24
  • if the index belongs to the list, that is. Commented Feb 5, 2018 at 16:24
  • So I need to do something like, L[bisect(L,n)-1] == n ? Commented Feb 5, 2018 at 16:52
  • @Johan: use bisect_left(), and you don't have to subtract. You'll have to account for the possibility that the resulting index is 1 higher than the last valid index. So use idx = bisect_left(L, n) and then use idx < len(L) and L[idx] == n. Commented Feb 5, 2018 at 17:02

0