"Compressing" a list of integers
<p>I have a list of integers as follows:</p>

<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>

<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>

<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>

<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>

<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>

<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>

<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>

<p>Thanks in advance!</p>

<p>First off, your requested results are not valid python.  I'm going to assume that the following format would work for you:</p>

<pre><code>my_new_list = [ ((0,3),2), ((4,4),3), ((5,5),4), ((6,7),2), ((8,9),4), ((10,10),3) ]
</code></pre>

<p>Given that, you can first transform <code>my_list</code> into a list of <code>((index,index),value)</code> tuples, then use <code>reduce</code> to gather that into ranges:</p>

<pre><code>my_new_list = reduce(
        lambda new_list,item:
            new_list[:-1] + [((new_list[-1][0][0],item[0][1]),item[1])]
                if len(new_list) &gt; 0 and new_list[-1][1] == item[1]
            else new_list + [item]
        , [((index,index),value) for (index,value) in enumerate(my_list)]
        , []
)
</code></pre>

<p>This does the following:</p>

<ol>
<li><p>transform the list into <code>((index,index),value)</code> tuples:</p>

<pre><code>[((index,index),value) for (index,value) in enumerate(my_list)]
</code></pre></li>
<li><p>use <code>reduce</code> to merge adjacent items with the same value:  If the list being built has at least 1 item and the last item in the list has the same value as the item being processed, reduce it to the list minus the last item, plus a new item consisting of the first index from the last list item plus the second index of the current item and the value of the current item.  If the list being built is empty or the last item in the list is not the same value as the item being processed, just add the current item to the list.</p></li>
</ol>

<p><em>Edited to use <code>new_list</code> instead of <code>list</code> as my lambda parameter; using <code>list</code> as a parameter or variable name is bad form</em></p>

python list