Topics: AI | Data Science | Data Visualization | Deep Learning | Machine Learning | NLP | Python | R | Statistics

KDnuggets Home » News » 2021 » Jun » Tutorials, Overviews » How to Make Python Code Run Incredibly Fast ( 21:n21 )

Silver BlogHow to Make Python Code Run Incredibly Fast


In this article, I have explained some tips and tricks to optimize and speed up Python code.



By Pralabh Saxena, Software Developer

Figure
Photo by David Clode on Unsplash

 

Python is one of the most popular programming languages among developers. It is used everywhere, whether it’s web development or machine learning.

There are many reasons for its popularity, such as its community support, its amazing libraries, its wide usage in Machine Learning and Big Data, and its easy syntax.

Despite having these many qualities, python has one drawback, which is its slow speed. Being an interpreted language, python is slower than other programming languages. Still, we can overcome this problem using some tips.

In this article, I will share some python tricks using which we can make our python code run faster than usual. Let’s get started!

 

1. Proper algorithm & data structure

 
Each data structure has a significant effect on runtime. There are many built-in data structures such as list, tuple, set, and dictionary in python. Most of the people use list data structure in all the cases.

In python, sets and dictionaries have O(1) lookup performance as they use hash tables for that. You can use sets and dictionaries instead of lists in the following cases:

  • You do not have duplicate items in the collection.
  • You need to search items repeatedly in the collection.
  • The collection contains a large number of items.

You can see the time complexity of different data structures in python here:

Time Complexity via Python Wiki
This page documents the time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython...

 

2. Using built-in functions and libraries

 
Python’s built-in functions are one of the best ways to speed up your code. You must use built-in python functions whenever needed. These built-in functions are well tested and optimized.

The reason these built-in functions are fast is that python’s built-in functions, such as min, max, all, map, etc., are implemented in the C language.

You should use these built-in functions instead of writing manual functions that will help you execute your code faster.

Example:

newlist = []

for word in wordlist:
    newlist.append(word.upper())


A better way to write this code is:

newlist = map(str.upper, wordlist)


Here we are using the built-in map function, which is written in C. Therefore, it is much faster than using a loop.

 

3. Use multiple assignments

 
If you want to assign the values of multiple variables, then do not assign them line by line. Python has an elegant and better way to assign multiple variables.

Example:

firstName = "John"
lastName = "Henry"
city = "Manchester"


A better way to assign these variables is:

firstName, lastName, city = "John", "Henry", "Manchester"


This assignment of variables is much cleaner and elegant than the above one.

 

4. Prefer list comprehension over loops

 
List comprehension is an elegant and better way to create a new list based on the elements of an existing list in just a single line of code.

List comprehension is considered a more Pythonic way to create a new list than defining an empty list and adding elements to that empty list.

Another advantage of list comprehension is that it is faster than using the append method to add elements to a python list.

Example:

Using list append method:

newlist = []
for i in range(1, 100):
    if i % 2 == 0:
        newlist.append(i**2)


A better way using list comprehension:

newlist = [i**2 for i in range(1, 100) if i%2==0]


Code looks cleaner when using list comprehensions.

 

5. Proper import

 
You should avoid importing unnecessary modules and libraries until and unless you need them. You can specify the module name instead of importing the complete library.

Importing the unnecessary libraries will result in slowing down your code performance.

Example:

Suppose you need to find out the square root of a number. Instead of this:

import math
value = math.sqrt(50)


Use this:

from math import sqrt
value = sqrt(50)


 

6. String Concatenation

 
In python, we concatenate strings using the ‘+’ operator. But another way to concatenate the strings in python is using the join method.

Join method is a more pythonic way to concatenate strings, and it is also faster than concatenating strings with the ‘+’ operator.

The reason why the join() method is faster is that the ‘+’ operator creates a new string and then copies the old string at each step, whereas the join() method does not work that way.

Example:

output = "Programming" + "is" + "fun


Using join method:

output = " ".join(["Programming" , "is", "fun"])


The output of both methods will be the same. The only difference is that the join() method is faster than the ‘+’ operator.

 

Conclusion

 
That’s all from this article. In this article, we have discussed some tricks that can be used to make your code run faster. These tips can be used especially with competitive programming where the time limit is everything.

I hope you liked this article. Thanks for reading!

 
Bio: Pralabh Saxena is a software developer with 1 year of experience. Pralabh writes articles on topics such as Python, Machine Learning, Data Science, and SQL.

Related:


Sign Up

By subscribing you accept KDnuggets Privacy Policy