Writing efficient Python code — Headstart on writing Pythonic Codes

Abhinav Koul
3 min readOct 21, 2020
Photo by Maxwell Nelson on Unsplash

Python is a highly readable general-purpose coding language designed keeping readability in mind making it one of the easiest languages to learn.
Due to this many people prefer using Python over C++/C/Java for complicated tasks.

Problems writing in a language you don't understand!

Recently one of my classmates was doing some questions in Python as well as C++ and he complained that Python is way too slow for doing the same task in C++.

After going through his code I found out that he just converted the code written in C++ to Python. Now this is a major mistake nearly everyone makes, we need to understand that each language has its own pro’s and Con’s.

Writing Pythonic Code

PEP 20 describes the guiding principles for Python’s design into 20 aphorisms, only 19 of which have been written down.

Now to make our python code run at max efficiency we need:

  1. Focus on readability
  2. Using Python’s constructs as intended! (i.e. Pythonic)

Pythonic code makes us utilize the strength of the language to make the processing faster. As python was written keeping readability in mind, the way of writing things in python is different than other languages like C++/JAVA.

Example

Q1) Given an array of names, return another array of tuples having index and name of people.

  1. Non-Pythonic/Traditional way
Non-Pythonic/ General C++ Version

Here as we can see we used the for loop to our rescue similar to as in C++.

Although this code looks fine BUT this isn't the most efficient way to do this!

2. Pythonic/Efficient way

a) 1st Solution: Used List comprehension along with for loop
Even though this solution is pythonic and a lot better than the Non-Pythonic solution, but still this is a bit slow as we are again using a for loop.

b) 2nd Solution: Used List Comprehension and Built-In Enumerate fn and unpacked the object created using (*).

Here 2nd solution is the most pythonic way to solve the problem.

Q2) Given an array of numbers, you need to return another array having just the doubled values.

Now here again our initial instinct is using a for loop(a habit from using a language like C++/JAVA).

For context see the picture, here as we can see there are different types of people having their own pros and cons!
All we need is to identify and utilize that extraordinary stuff!

Similarly Python isn’t C++/Java, thus we need to treat it differently!

So after gaining insights from this, we progress towards the power of python — LIST COMPREHENSION.
Let's look at the solution now:

Hope you were able to understand the basics of writing Pythonic Codes.

Always remember :

Simple is better than Complex — 3rd ZEN of Python

Funny enough this applies everywhere in life!

--

--