Single or Multiple Lines: What's Better For Python Code Readability?

Avatar
Posted on Oct 23, 2020

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.

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

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. 

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 more sparse.

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. 

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 Author

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 airbnb Alex Baransky alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus API Application artist aws 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 Bundles California Cancer Research capstone Career Career Day citibike clustering Coding Course Demo Course Report D3.js data Data Analyst data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization Deep Learning Demo Day Discount dplyr employer networking feature engineering Finance Financial Data Science Flask gbm Get Hired ggplot2 googleVis Hadoop higgs boson Hiring hiring partner events Hiring Partners Industry Experts Instructor Blog Instructor Interview Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter lasso regression Lead Data Scienctist Lead Data Scientist leaflet linear regression Logistic Regression machine learning Maps matplotlib Medical Research Meet the team meetup Networking neural network Neural networks New Courses nlp NYC NYC Data Science nyc data science academy NYC Open Data NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time Portfolio Development prediction Prework Programming PwC python python machine learning python scrapy python web scraping python webscraping Python Workshop R 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 Selenium sentiment analysis Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau team TensorFlow Testimonial tf-idf Top Data Science Bootcamp twitter visualization web scraping Weekend Course What to expect word cloud word2vec XGBoost yelp