Now that I have a better understanding of your definition of groups, I think this relatively simple answer will not only work, but also very quickly:
from collections import defaultdict a = [0, 1, 3, 4, 6, 7, 8, 10, 14] chunk_size = 5 buckets = defaultdict(list) for n in a: buckets[n/chunk_size].append(n) for bucket,values in sorted(buckets.iteritems()): print '{}: {}'.format(bucket, values)
Output:
0: [0, 1, 3, 4] 1: [6, 7, 8] 2: [10, 14]
source share