Python favours explicit over implicit. Your options are to explicitly use the bisect
module if you know your data is sorted, or create a subclass of list
that implements __contains__
by using that module.
For example:
import bisect
class SortedList(list):
def __contains__(self, elem):
idx = bisect.bisect_left(self, elem)
return idx < len(self) and self[idx] == elem
could be used as a substitute for list
, and in
will use __contains__
automatically. You'd probably want to override __setitem__
, .extend()
and .append()
to maintain the list in sorted order, too.