I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as from A to B
, which represent rang
Without writing your own class, the function seems to be the way to go. What i can think of at most is not storing actual lists, just returning generators for the range you care about. Since we're now talking about usage syntax - here is what you could do
def closed_range(slices):
slice_parts = slices.split(':')
[start, stop, step] = map(int, slice_parts)
num = start
if start <= stop and step > 0:
while num <= stop:
yield num
num += step
# if negative step
elif step < 0:
while num >= stop:
yield num
num += step
And then use as:
list(closed_range('1:5:2'))
[1,3,5]
Of course you'll need to also check for other forms of bad input if anyone else is going to use this function.