top of page

How to make your Python Code Run fast

Python is a high-level, general-purpose programming language and the most popular programming language in the world. This language is used because of its simple syntax and good libraries. In this article, we will guide you on how to make your Python Code Run fast.


To code faster, one has to be efficient; that is, no wasted effort or motion. This can mean everything from typing to tools to thinking. But most of our work as programmers isn't typing, or compiled—it's thinking. To think faster, you have to learn more patterns and relationships.


Make your Python Code Run fast:


1. Do not use dot operation

Try to avoid the dot operation while using any class of module. Instead of that try to import that class from that library. Because when you use the dot operation on the library it first calls __getattribute()__ which will then use dictionary operation which costs time.


Example:

#Don't use that 
import time
time.sleep(10)#Use that 
from time import sleep
sleep(10)

2. Use Good 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 people use a list data structure in all 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 for items repeatedly in the collection.

  • The collection contains a large number of items.


3. Use Join for String Concatenation

In python, we concatenate strings using the ‘+’ operator. But another way to concatenate the strings in python is using the join method. The 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:

Without join method:

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

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

4. 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"

Use this:

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

5. 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())

Use this:

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.

6. Use 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. It is considered a more Pythonic way to create a new list than defining an empty list and adding elements to that empty list.


Example:


Using list append method:

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

Use this:

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

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

import math value = math.sqrt(50)

Use this:

from math import sqrt value = sqrt(50)

8. Do not use global variables

Python has a global keyword to declare global variables. But global variables take higher time during operation than local variables. So, do not use global variables if it is not necessary.



The Tech Platform

0 comments
bottom of page