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>Your code is really confusing with all these counters. What you need to do is implement the algorithm as it is defined. You need just a single index <code>i</code> which keeps track at what position of the list you are currently at and at each step compare the number to the previous number.</p>

<ul>
<li>if they are equal, then increment the counter</li>
<li>if they are not equal then add the new pair of the tracked number with the count and reset the counter to 0 and set the new tracking number to the current number.</li>
</ul>

python encoding compression