DEV Community

Cover image for Tips to make Python Code faster

Tips to make Python Code faster

Aman Gupta
I am an Data Scientist and a Engineering Student . Looking for an internship in Data Science , Machine Learning and Deep Learning.
・2 min read

At this time we need everything fast and this thing also applies to programming. So we can talk here about how can we make the python program run Faster.

The first way to make a program faster is to understand the Data Structure that which one is fast and which is slow. So let's talk about python list and dict. For searching an element, which one is Faster?

When we searching an element in a list then we have only one way that is by accessing each item from the 0th index to the last index but the dictionary utilizes a data structure called a hashmap (Python dictionaries are optimized versions), and a key will be converted using a hash algorithm from a string (or whatever) into an integer value, and it is a couple of very simple calculations to take that integer and find the right place in the dictionary to look. So the dict Data Structure is faster than list for searching elements and by using a faster data structure we can make our code faster.

Another way to do reduce the run time of a python code is by reducing Memory footprint.
For example:
Alt Text
This is inefficient because a new string gets created upon each pass. Use a list and join it together:
Alt Text
Similarly, avoid the + operator on strings:
Alt Text

The next way to speedup python code is by using built-in functions because built-in functions like sum, max, any, map, etc are implemented in C. They are very efficient and well tested. These functions reduce the runtime of the code and make the program Faster.

Discussion (0)