How do I remove consecutive duplicates from a list?
<p>How do I remove consecutive duplicates from a list like this in python?</p>

<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>

<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>

<p>I want the result to be like this:</p>

<pre><code>newlst = [1,2,4,1,3,5]
</code></pre>

<p>Would you also please consider the case when I have a list like this 
 <code>[4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3]</code> 
and I want the result to be <code>[4,2,3,3]</code> 
rather than <code>[4,2,3]</code> .</p>

<p><a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby()</a> is your solution.</p>

<pre><code>newlst = [k for k, g in itertools.groupby(lst)]
</code></pre>

<hr>

<p>If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that does it:</p>

<pre><code>import itertools

def special_groupby(iterable):
    last_element = 0
    count = 0
    state = False
    def key_func(x):
        nonlocal last_element
        nonlocal count
        nonlocal state
        if last_element != x or x &gt;= count:
            last_element = x
            count = 1
            state = not state
        else:
            count += 1
        return state
    return [next(g) for k, g in itertools.groupby(iterable, key=key_func)]

special_groupby(lst)
</code></pre>

<p>OR</p>

<pre><code>def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

newlst = list(itertools.chain.from_iterable(next(zip(*grouper(g, k))) for k, g in itertools.groupby(lst)))
</code></pre>

<p>Choose whichever you deem appropriate. Both methods are for numbers > 0.</p>

python