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>You'd probably want something like this.</p>

<pre><code>lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2]
prev_value = None
for number in lst[:]: # the : means we're slicing it, making a copy in other words
    if number == prev_value:
        lst.remove(number)
    else:
        prev_value = number
</code></pre>

<p>So, we're going through the list, and if it's the same as the previous number, we remove it from the list, otherwise, we update the previous number. </p>

<p>There may be a more succinct way, but this is the way that looked most apparent to me. </p>

<p>HTH.</p>

python