3 Python Tricks for Better Code

https://miro.medium.com/max/1200/0*eTiwa_LD2yHYly8s

Original Source Here

List Comprehensions

List comprehension is the best and the real Pythonic 💡 way to create lists based on the existing lists.

To make the words more clear, here is an example. Let’s create a simple list of strings.

listofnames = ["apple", "orange100", "banana2",
"pineapple", "10grapes", "jackfruit"]

Next, I want to create a list of all the strings from the recently created listofstrings in the upper case if the string is purely alphabetic.

The task can be completed using for loop and if statements, but it is not the Pythonic way. Rather, use list comprehension as shown below to keep the code length limited to a single line.

new_list = [name.upper() for name in listofnames if name.isalpha()]

Making understanding even simpler, let’s compare list comprehension with for loop and if statement.

Comparison of List Comprehension and For loop | Image by Author

As seen in the above picture, the innermost element in the for loop will be the first element in the list comprehension.

However, list comprehensions are not the right choice in all situations. In certain scenarios, it can make your code run slow and consume more memory. 🚩

Advantages and Disadvantages of List Comprehensions | Image by Author

Depending on the complexity of the program, you have to choose between list comprehension and the for loop. The important thing is to write a code that is easy to understand and modify.

Dictionary to replicate Switch-Case statement

Use a dictionary 📚 to replicate the Switch-Case and multiple if-elif-else statements in Python.

Unlike other programming languages, Python does not support the Switch-Case statements. This can be always implemented using the if-elif-else statement.

Replacing multiple if-elif-else statements by Dictionary made my program 440X faster than its last version.

Let’s see this example.
The variable action is the Switch and the value it takes is the Case. Depending on the value, different paths of the program are executed.

Switch-Case Statement | Image by Author

Certainly, this can be implemented using if-else statements. But, the code readability will start going down with increasing complexity.

Here is how this can be implemented in if-else .

Using If-Else statement to replicate Switch-Case | Gist by Author

the statementif-elif-else alone takes 11 lines of code with good code readability and this will always keep growing with increasing cases.

A better way, use a dictionary of all the cases. 📚 See the example below.

Using Directory to replicate Switch-Case | Gist by Author

Simple! The code length is reduced and still code readability is better than if-elif-else .

In more complex scenarios, these lambda functions can be directly replaced by user-defined functions. Hence, with increasing cases the code length will always increase by only 1 line.

Furthermore, depending on the complexity of your code, a dictionary can improve the execution time for the complete code. In my project, it made my code 440X faster.

Advantages of using Dictionary | Image by Author

Ternary Conditionals

Use Python Conditionals when you want a line or block of code to be executed when a certain condition is true.

Usually, this is done using a if statement. However, an if takes at least 2 lines of code. There is a more concise way of writing such conditional statements — Ternary operator in Python.

As its name suggests, the Ternary operator takes three parameters — the expression to be evaluated if the condition is true, condition, expression to be evaluated if the condition is false.

Python Ternary Operator Syntax | Image by Author

Let’s take the example of writing a small code to check if the person is a senior citizen or not, based on his age. Simply, initiating a variable age.

age = 79

Using ternary conditional, this code is reduced to only a single line.

print("Senior Citizen") if age>60 else print("Not a Senior Citizen")

Whereas, the same logic can be implemented in the if-else as below.

if age>60:
print("Senior Citizen")
else:
print("Not a Senior Citizen")

Clearly, Ternary conditional makes the code 75% shorter and also improves the readability.

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: