Python Project – Morse Code Encoder – Part 2

In the last post, Python Project – Morse Code Encoder, we looked at creating a Morse Code encoder. The application works fine, but how can we streamline it? Let’s take a look at specific parts of the code base and see what we could do.

The for-loop

As a refresher, our code base from the previous post for the for-loop is:

encoded_mc = []
for char in code:
    encoded_mc.append(char_to_code[char])

On the surface, it is doing what it is supposed to do; we have an empty list called encoded_mc , and we loop through every character in what the user inputs and append that to the empty list on every iteration. What if I said we could do this exact thing in one line? We can do this with the help of a list comprehension. A list comprehension is a way to write a list from a for-loop easily. You can read more here: Python Comprehensions.

If we were to break down a list comprehension:

new_list = [new_item for item in list]

That would be the above, and we would need to fill in each item:

  • list
    • This is the iterator we are taking in. In our case, it is the variable code where the individual running the application will input what they want to encode as Morse Code. In this example
  • item
    • This is the value we are going to pass into our for-loop
  • new_item
    • We are evaluating the item against this expression to add to the new list.

Taking all of this into consideration, when we are writing a list comprehension for encoding Morse Code from our previous for-loop

# Original For-Loop
encoded_mc = []
for char in code:
    encoded_mc.append(char_to_code[char])
 
# New List Comprehension
encoded_mc = [char_to_code[char] for char in code]

This simplifies the code that we are writing for the for-loop

Returning a String vs a List

We are returning our Morse code as a list, but what if we wanted to make it look cleaner and have it return as a string? There is a string method that we can run to turn our list back into a string. The method is the .join() method, which allows you to take an iterable and join it into a single string. For example, if we have the following and want to convert it into a string with a white space between them:

my_list = ['Apple', 'Orange', 'Grape']
my_string = ' '.join(my_list)
print(my_string)
# Apple Orange Grape

With our code, we can do this one of two ways;

# Create a new variable for the string
encoded_mc = [char_to_code[char] for char in code]
new_morse_code = ' '.join(encoded_mc)
 
# Incorporate join to the list comprehension
 encoded_mc = ' '.join([char_to_code[char] for char in code])

These are just a few ways we can optimize our code. Did I miss any? Let me know in the comments if you can think of another way to optimize the code.