"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>You could use enumerate with a generator function</p>

<pre><code>def seq(l):
    it = iter(l)
    # get first element and set the start index to 0.
    start, prev = 0, next(it)
    # use enumerate to track the rest of the indexes
    for ind, ele in enumerate(it, 1):
        # if last seen element is not the same the sequence is over
        # if start i == ind - 1 the sequence had just a single element.
        if prev != ele:
            yield ("{}-{}, {}".format(start, ind - 1, prev)) \
                if start != ind - 1 else ("{}, {}".format(start, prev))

            start = ind
        prev = ele
    yield ("{}-{}, {}".format(start-1, ind-1, prev)) \
        if start != ind  else ("{}, {}".format(start, prev))
</code></pre>

<p>Output:</p>

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

In [4]: list(seq(my_list))
Out[4]: ['0-3, 2', '4, 3', '5, 4', '6-7, 2', '8-9, 4', '10, 3']
</code></pre>

<p>I was going to use  <em>groupby</em> but will be faster.</p>

<pre><code>In [11]: timeit list(seq(my_list))
100000 loops, best of 3: 4.38 Âµs per loop

In [12]: timeit itools()

100000 loops, best of 3: 9.23 Âµs per loop
</code></pre>

python list