DEV Community

Cover image for How to make your python code faster
Angkon-Dutta-Joy
Angkon-Dutta-Joy

Posted on

How to make your python code faster

Python is a popular language with simple syntax and a wealth of libraries that is widely used in competitive programming. However, when it comes to solving complex algorithmic problems, many programmers struggle with the issue of Time Limit Exceeded. While it's true that Python isn't the fastest language out there, there are several techniques you can use to write efficient code and ensure that it gets accepted.
Image description

Use the appropriate data structure:

Using the correct data structure can have a significant impact on runtime. While Python has built-in data structures such as lists, tuples, sets, and dictionaries, many people tend to use lists in all cases. However, it's essential to use the right data structure depending on your task. For example, iterating over a tuple is often faster than iterating over a list.

Reduce the use of for loops:

As for loops are dynamic in Python, they take more time than while loops. Therefore, it's better to use while loops instead of for loops.

Use list comprehension:

List comprehension is a powerful tool that you should use instead of other techniques whenever possible. For example, if you need to list all the numbers between 1 and 1000 that are multiples of 3, list comprehension is a more efficient way to achieve this than using the append method.
Instead of

L = []
for i in range (1, 1000):
    if i%3 == 0:
        L.append (i)
Enter fullscreen mode Exit fullscreen mode

Use -

L=[i for i in range(1,1000) if i%3==0]
Enter fullscreen mode Exit fullscreen mode

Use multiple assignments:

Using multiple assignments can save time by assigning variables together in a single line instead of one by one.

#instead of 
a = 1
b = 2
c = 3
d = 4
#write
a,b,c,d=1,2,3,4
Enter fullscreen mode Exit fullscreen mode

Avoid using global variables:

Global variables take more time to operate than local variables. Therefore, it's better not to use global variables unless necessary.

Use library functions:

Whenever possible, use library functions instead of writing your functions manually. Library functions are highly efficient and often impossible to match in terms of coding efficiency.

Concatenate strings with join():

While you can concatenate strings with the + operation in Python, it's better to use the join() method as it's faster. The + operator creates a new string and copies the old content at each step, while join() doesn't work that way.

#instead of 
concatenated_String = "Python " + "is " + "fun."

#write
concatenated_String = " ".join (["Python", "is", "fun."])
Enter fullscreen mode Exit fullscreen mode

Use generators:

If you have a large amount of data in your list and need to use only one data at a time and for once, then use generators as they can save you time.

Avoid using dot operations:

Using dot operations can be time-consuming, as they first call getattribute() or getattr() and then use dictionary operations.

#instead of 
import math
val = math.sqrt(60)

#write
from math import sqrt
val = sqrt(60)
Enter fullscreen mode Exit fullscreen mode

Use 1 for infinity loops:

Using while 1 instead of while True can reduce runtime.

While 1:
    ......
Enter fullscreen mode Exit fullscreen mode

Try a different approach:

Sometimes, taking a different approach to writing code can lead to better performance. For example, instead of using nested if statements, you can use a single if statement with logical operators.

#instead of 
if a_condition:
    if another_condition:
        do_something
else:
    raise exception
#write
if (not a_condition) or (not another_condition):
    raise exception
do_something
Enter fullscreen mode Exit fullscreen mode

Use sys for faster input:

Use the code below to get faster input time

import sys
input= sys.stdin.readline 
Enter fullscreen mode Exit fullscreen mode

Use speed-up applications:

To decrease runtime, you can use projects like Pypy and Numba. These applications can reduce the runtime of your program.

Use special libraries to process large datasets:

Python may not be the fastest language for processing large datasets, but you can use packages and modules written in C/C++, such as Numpy, Scipy, and Pandas, to optimize your code.

Use the latest release of Python:

Python is regularly updated and optimized, with each new release being faster than the previous one. Therefore, it's important to always use the latest version of Python.

These are just a few ways to speed up your Python code. There are several other techniques that you can use, so be sure to use a search engine to find them and write efficient code!

Top comments (0)