"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>Some good answers here, and thought I would offer an alternative. We iterate through the list of numbers and keep an updating <code>current</code> value, associated with a list of indicies for that value <code>current_indicies</code>. We then look-ahead one element to see if the consecutive number <strong>differs</strong> from <code>current</code>, if it does we go ahead and add it as a '<em>compressed number</em>'. </p>

<pre><code>def compress_numbers(l):
    result = []
    current = None
    current_indicies = None
    for i, item in enumerate(l):
        if current != item:
            current = item
            current_indicies = [i]
        elif current == item:
            current_indicies.append(i)
        try:
            if l[i+1] != current:
                result.append(format_entry(current_indicies, current))
        except:
            result.append(format_entry(current_indicies, current))
    return result

# Helper method to format entry in the list.
def format_entry(indicies, value):
    i_range = None
    if len(indicies) &gt; 1:
        i_range = '{}-{}'.format(indicies[0], indicies[-1])
    else:
        i_range = indicies[0]
    return '{},{}'.format(i_range, value)
</code></pre>

<p><strong>Sample Output:</strong></p>

<pre><code>&gt;&gt;&gt; print compress_numbers([2, 2, 2, 2, 3, 4, 2, 2, 4, 4, 3])
['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>

python list