Run Length Encoding in Python

In this tutorial, we are going to learn how to create a run-length encoding in Python. Given a string return a new string containing char and frequency.

For example, the string tutorialspoint will be encoded as t3u1o2r1i2a1l1s1p1n1. The order is every char+frequency. Join all of them and return. See the steps below to write the program.

  • Write the function with the name run_length_encoding.

  • Initialize a dictionary with OrderedDict to get an initial count of chars as 0.

  • Iterate over every character of the string and increment the count in the dictionary.

  • Join all the chars and their frequencies. And print it.

  • Initialize the strings and invoke the function.


Let's see the code for the above text.

# importing the collections
import collections
# function
def run_length_encoding(string):
   # initialzing the count dict
   count_dict = collections.OrderedDict.fromkeys(string, 0)
   # iterating over the string
   for char in string:
      # incrementing the frequency
      count_dict[char] += 1
   # initializing the empty encoded string
   encoded_string = ""
   # joining all the chars and their frequencies
   for key, value in count_dict.items():
      # joining
      encoded_string += key + str(value)
      # printing the encoded string
# initializing the strings
string = "tutorialspoint"
# invoking the function
# another string
string = "aaaaaabbbbbccccccczzzzzz"


If you run the above code, you will get the following output.



If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 12-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started