How to Simplify Your Python Code for Optimal Readability

and
Posted on Oct 16, 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 a previous article, we discussed how and why you should be explicit while writing your Python code. That covered another avenue of improving your Python code’s readability, including naming conventions, calling objects from other modules and packages, and more. In this article, we’ll be discussing why writing simpler code will help not only with the reader’s comprehension of your syntax, but it will also force you to think about problems in a way that is easier to explain to those who may not be as technically savvy.

You should always try to write simple rather than overcomplicated code. Recognizing when you can simplify your code comes with practice and experience. There are many built-in Python functions that you can use to enable simplification. Try to become familiar with these functions to avoid needing to reinvent the wheel. Remember that you don’t need to memorize these functions and what they do, but you must know they exist so you can look them up when they’re needed. Ignorance is your greatest enemy when you’re a programmer; it makes working on problems much more difficult.

Bad Examples

How to Simplify Your Python Code for Optimal Readability

How to Simplify Your Python Code for Optimal Readability

All of the examples in the cell above try to perform operations from scratch. While writing your Python code, you’ll want to look for more β€œPythonic” ways to write. Your syntax will look more professional and, at the same time, be easier to read and understand.Β 

To avoid wasting time and effort, don’t try to reinvent how something works. There are almost always existing functions to use.

In the first example above, we’re trying to compute a cumulative sum. What is written here might look good to a novice programmer, but a more experienced coder will recognize a sum function that can be implemented.Β 

Trying to recreate functions from scratch will also cause your code to run slower than the code that is already implemented. Many of the built-in functions in Python are written in a more machine-level language that is much faster and more optimized for these operations. In this way, there will be an efficiency advantage when using built-in functions rather than defining your own. This efficiency can also be seen when using functions and methods in the NumPy and pandas packages. Sometimes you will need to define your own function when you need to accomplish a specific task, but try to use already defined functions when possible rather than creating your own.

The fourth example is from CodeWars, which is an excellent website for coding challenges. There is a class called Counter within the collections module that’s great for turning an iterable of elements into a dictionary representing the frequency of each unique element.Β 

There is a more straightforward way to do this, though, shown in #4 in the following example.

Good Examples

How to Simplify Your Python Code for Optimal Readability

How to Simplify Your Python Code for Optimal Readability

All of the examples above use built-in Python functions to simplify the code. The zip function is another handy tool. It takes two iterables, then zips them together, and uses the dict function to convert the tuples of key/value pairs into a dictionary. We stress the usage of the zip function in much more detail in our data science bootcamps.Β 

It’s important to implement these built-in Python functions in your code to ensure optimal readability and be as efficient as possible, to make sure your code looks clean and organized.Β 

The way you can use what you’ve learned in your work is simply by practicing. Always make a note of the different functions and understand that they’re available to you. Again, it’s unnecessary to memorize them all, but it’s essential to know that they exist.Β 

For example, suppose you’re working on a project and remember that the string class has a method that counts the number of some characters within a string. In that case, you can quickly look that function up on Google or StackOverflow or any other mass information repository. Knowing that these functions exist makes them available to you, even if you don’t have them memorized. It’s acceptable to use Google to find more information about code; experienced programmers do it all the time! It’s a great way to discover new techniques and tools.

Though we’ve gone into some detail here, this is only scratching the surface of optimal code readability. We go into much deeper detail 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

Single or Multiple Lines: What’s Better For Python Code Readability? – AiProBlog.Com December 24, 2020
[…] 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 […]
Single or Multiple Lines: What's Better For Python Code Readability? December 23, 2020
[…] 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 […]
Single or Multiple Lines: What’s Better For Python Code Readability? – Data Science October 25, 2020
[…] 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 […]

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