[Solved] Python creating nested lists [closed]


You can use itertools.groupby to group everything into lists of adjacent identical values, then unpack the lists of length one out of the nested lists:

from itertools import groupby

def group_adjacent(iterable):
    lists = (list(g) for k, g in groupby(iterable))
    return [subl[0] if len(subl) == 1 else subl for subl in lists]

group_adjacent([1,2,4,5,5,7,6,6,6])
# [1, 2, 4, [5, 5], 7, [6, 6, 6]]

solved Python creating nested lists [closed]