def sub(x):
    return x[1] - x[0]
a = [5, 3, 7, 4, 1, 2, 9, 10]
ranges = []
for k, iterable in groupby(enumerate(sorted(a)), sub):
    rng = list(iterable)
if len(rng) == 1:
    s = str(rng[0][1])
else:
    s = '%s-%s' % (rng[0][1], rng[-1][1])
ranges.append(s)
print(ranges)
How to do an inverse `range`, i.e. create a compact range based on a set of numbers?