Python Code Readability - What Type of Line is Better?

Posted on Oct 23, 2020

The skills the authors demonstrated here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Introduction to Python Codes

In another article, we discussed how to simplify your Python code for optimal readability. That piece covered why writing simpler code will help with the reader’s comprehension of your syntax and force you to think about problems in a way that is easier to explain to those who may not be as technically savvy. This article will cover how to separate your code into multiple lines and why it will strengthen your Python code. 

Although you should always try to keep your code concise, you don’t want to do it at the expense of readability. Don’t try to write code all on one line when you can write the same code on multiple lines in a more interpretable way. This will confuse anyone reading it when they try to decipher your dense lines of code. 

There’s a delicate balance here that you should strive to reach. As you become more experienced in coding, you might be more inclined to start condensing things by writing them on one line, but don’t go overboard. Forcing everything onto one line will not always portray you as a more advanced coder. It will have the opposite effect if doing so makes the syntax challenging to read. 

Don’t confuse aiming for sparsity with reducing the efficiency of your code. Your goal should always be efficiency but try to do so in a way where the code is still easy to read.

Examples of Python Codes - Pt. 1

Let’s go over a few examples of dense code. Then we’ll talk about how to improve them.

Python Code Readability - What Type of Line is Better?

The first example prints a string that tells the user how a certain number of bytes can represent many possible values. It is an extremely long print statement, which makes it hard to read. It’s so long that you would need to scroll to the right to view the whole statement! 

For interpretability, you can break this string into multiple steps. Even though it may be nice to solve a problem using one line of code, you don’t want to make it difficult for someone to read through this line and understand what you’re attempting to do. 

The second example enters a gray area. This type of coding can be okay, but you should avoid making your conditions as complicated as they are here. You could write this in separate statements as opposed to one long expression.

Examples of Python Codes - Pt. 2

The third example is challenging to read. It uses both map and filter, with multiple lambda functions, in one line of code. It may solve the problem, but it scores no points for readability.

Now let’s fix these examples by making the dense code a little sparser.

Python Code Readability - What Type of Line is Better?

The first example shows our long bytes values print statement broken down into multiple steps. This allows the reader to easily follow the step-by-step process, where before they would have to spend some time deciphering the long line of code.

For the second example, we wrote out “if-else” statements, which are more logically straightforward than the original expression of nested conditionals. This example can be done either way. What you choose to do comes down to personal preference, but if you want your colleagues to follow your logic easily, the if-else statements accomplish that goal.

The last example is split into multiple steps to make it simpler to read. What makes this example even better is the use of list comprehension. With this, you can do the equivalent of both map and filter operations in a single, logically simple step. Hopefully, this example shows that one-line solutions are not necessarily wrong, but you need to consider your solution’s complexity. 

Let’s look at if-else statements for another example. If-else one-liners are generally fine to use if the conditions aren’t too complicated. Below is an example of this. If the conditions get more complicated than this example, you should use the traditional multi-line if-else statements. 

Python Code Readability - What Type of Line is Better?

Conclusion to Python Code Readability

Everything discussed in this article is only one small peek at the much greater topic of optimal code readability. This, along with many other coding best-practices, is stressed in our programs and bootcamps. 

Ready to advance your programming skills to the next level? Check out this three-course program focused on building and advancing your Python Programming skills, or start your journey towards data science mastery by enrolling in our upcoming remote live and online data science bootcamps.

About Authors

Alex Baransky

Alex graduated from Columbia University with training in natural and technical sciences. He enjoys finding ways to utilize data science to answer questions efficiently and to improve the interpretability of results. Alex takes pride in his ability to...
View all posts by Alex Baransky >

Leave a Comment

No comments found.

View Posts by Categories

Our Recent Popular Posts

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI