nctn = open("nctn.txt").readlines() nums = [int(n.strip()) for n in nctn] nums = sorted(nums) print(len(nums)) print(nums[:20]) def ranges(nums): '''Return a list of continuous ranges (min, max values) from a list of integers.''' rgs = [[nums[0]]] # these two make the code more readable and, incidentally, faster FIRST, LAST = 0, -1 for n in nums: if rgs[LAST][LAST] == n - 1: if rgs[LAST][FIRST] == n -1: rgs[LAST].append(n) if rgs[LAST][FIRST] < n - 1: rgs[LAST][LAST] = n elif rgs[LAST][LAST] < n -1: rgs.append([n]) return rgs rgs = ranges(nums) for r in rgs: try: print('{} - {}: {} numbers'.format(r[0], r[1], r[1] - r[0] + 1)) except IndexError: print('{}: 1 number'.format(r[0])) %timeit rgs = ranges(nums)