There is a list

list = [1,1,1,2,3,4,2,2,2] 

It is necessary to "merge" neighboring elements to get

 list = [1,2,3,4,2] 

How can I solve this problem?

    2 answers 2

    The easiest way is to use groupby . It is intended for such cases - it returns an iterator with consecutive elements and their number.

     from itertools import groupby old_list = [1,1,1,2,3,4,2,2,2] groupped = groupby(old_list) print([elem for elem, grouper in groupped ]) >>> [1, 2, 3, 4, 2] 

    If you need to know the number of consecutive elements, you can do this:

     for elem, grouper in groupped : print(elem, len(list(grouper))) >>> 1 3 >>> 2 1 >>> 3 1 >>> 4 1 >>> 2 3 
    • A plus. You can also: uniq = map(itemgetter(0), groupby(list_)) - jfs

    The simplest option for beginners:

     list = [1,1,1,2,3,4,2,2,2] result = [] prev = None for a in list: if a != prev: result.append(a) prev = a print(result) 

    But the variant with the same logic, but more complicated, with list generators:

     list = [1,1,1,2,3,4,2,2,2] def gen(lst): prev = None for a in lst: if a != prev: prev = a yield a print([x for x in gen(list)]) 
    • OrderedDict will eat all duplicates, not only consecutive ones - m9_psy
    • @ m9_psy Oops ... Right. Something I'm a moron today ... - user194374