Data Compression Model
<p>I am working on an exercise where we are to model Data Compression via a list. Say we were given a list: <code>[4,4,4,4,4,4,2,9,9,9,9,9,5,5,4,4]</code>
We should apply Run-length encoding, and get a new list of <code>[4,6,2,1,9,5,5,2,4,2]</code> where it shows how many 4's (6) 2's(1) 9's (5) 5's (2), etc.. jointly next to the integer. </p>

<p>So far I have the following code, however I am hitting a semantic error, and not sure how to fix it:</p>

<pre><code>  def string_compression(List):
      newlist=[]
      counter=0
      x=0
      for elm in List:
          prev_item= List[x-1]
          current_item=List[x]
          if prev_item == current_item:
              counter+=1
          else:
              newlist+=[current_item]+[counter]
              counter=0
</code></pre>

<p>P.S I am still a beginner, so I apologize if it is a 'dumb' question! I would really appreciate some help.</p>

<p>You're on the right track, but this is easier with an index-based loop:</p>

<pre><code>def rle_encode(ls):
    # Special case: the empty list.
    if not ls:
        return []

    result = []

    # Count the first element in the list, whatever that is.
    count = 1
    # Loop from 1; we're considering the first element as counted already.
    # This is safe because we know that the list isn't empty.
    for i in range(1, len(ls)):
        if ls[i] == ls[i - 1]:
            count += 1
        else:
            # Store the last run.
            result.append(ls[i - 1])
            result.append(count)
            # Count the current number.
            count = 1
    # Add the last run since we didn't get a chance to in the loop.
    result.append(ls[-1])
    result.append(count)

    return result
</code></pre>

python encoding compression