(Codewars) Range Extraction
Grouping

If you need to group anything using; groupby is probably the easiest way

Here we can use a itertools.groupby recipe to group the consecutive ranges:

&gt;&gt;&gt; for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):
...     print([x for _, x in g])
[-6]
[-3, -2, -1, 0, 1]
[3, 4, 5]
[7, 8, 9, 10, 11]
[14, 15]
[17, 18, 19, 20]


Yielding the correct representation

Now all is left is to check whether there are more then 2 items in the range, and return the range. Else return all the numbers in the range normally

We can make this a generator, which yields either the range or a number, and afterwards join them together.

Full Code

def group_consecutives(lst):
    for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):
        r = [x for _, x in g]
        if len(r) &gt; 2:
            yield f"{r[0]}-{r[-1]}"
        else:
            yield from map(str, r)

def range_extraction(lst):
    return ','.join(group_consecutives(lst))