As others have pointed out, you can use enumerate()
to get the indexes. I'd also argue that if you are treating the tuples as ranges, you should make them ranges. This then makes the check to see if the value is inside the range very intuitive: value in range
.
import itertools
seg = [(874, 893), (964, 985), (1012, 1031)]
ranges = list(itertools.starmap(range, seg))
def test(value):
for i, valueRange in enumerate(ranges):
if value in valueRange:
return i # + 1 if you want to index from 1 as indicated.
# You could add some special case handling here if there is no match, like:
# throw NoSuchRangeException("The given value was not inside any of the ranges.")
print(test(876)) # 0
print(test(1015)) # 1
Obviously using ranges has some cost (if you are in Python 2.x, this is comparatively huge because it will make actual lists of all the values, and unfortunately xrange()
return objects without __contains__()
implemented). If you are doing this kind of thing in lots of places, it's much nicer, however.
You may be able to just replace your tuple construction with range construction, depending on the situation, rather than doing the starmap.