There are a lot of similar question (like this one) but I did not find anything that suited my needs.
My objective is to remove groups of adjacent duplicates from a list.
For instance, if my list is
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'A', 'C', 'C']
my desired output is
['A', 'B', 'C', 'A', 'C']
i.e. every group of adjacent duplicates is removed, only one of their group remains.
My code so far involves a for cycle with a condition:
def reduce_duplicates(l):
assert len(l) > 0, "Passed list is empty."
result = [l[0]] # initialization
for i in l:
if i != result[-1]:
result.append(i)
return result
l = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'A', 'C', 'C']
print(reduce_duplicates(l))
# ['A', 'B', 'C', 'A', 'C']
It produces the expected output, but I think there is a native, optimized and elegant way to achieve the same result. Is it true?