NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship πŸ† Data Analytics Bootcamp
Free Lesson
Intro to Data Science New Release πŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See πŸ”₯
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular πŸ”₯ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New πŸŽ‰ Generative AI for Finance New πŸŽ‰ Generative AI for Marketing New πŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular πŸ”₯ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular πŸ”₯ Data Science R: Machine Learning Designing and Implementing Production MLOps New πŸŽ‰ Natural Language Processing for Production (NLP) New πŸŽ‰
Find Inspiration
Get Course Recommendation Must Try πŸ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Free Lessons
Intro to Data Science New Release πŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See πŸ”₯
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Student Works > How to Simplify Your Python Code for Optimal Readability

How to Simplify Your Python Code for Optimal Readability

Zoe Zbar and Alex Baransky
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

Zoe Zbar

View all posts by Zoe Zbar >

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

All Posts 2328 posts
Alumni 60 posts
APIs 40 posts
AWS 11 posts
Big Data 48 posts
Capstone 196 posts
Career Education 7 posts
Community 70 posts
Data Engineering 1 posts
Data Science News and Sharing 71 posts
Data Visualization 312 posts
Events 5 posts
Featured 37 posts
Hadoop 13 posts
Machine Learning 336 posts
Meetup 144 posts
Python 435 posts
R 395 posts
R Shiny 548 posts
R Visualization 440 posts
Spark 17 posts
Student Works 1610 posts
Tableau 12 posts
TensorFlow 2 posts
Web Scraping 480 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

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

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    © 2023 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application