How to Simplify Your Python Code for Optimal Readability

Avatar
Posted on Oct 16, 2020

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

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

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 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 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