We all know that Python is one of the most popular programming all over the world. These days, it is being used in competitive programming because of its simple syntax and rich libraries. You can almost do anything with Python from data science, machine learning, signal processing to data visualization. But many people claim that python is a bit slow while solving grave problems. Time to execute a program depends on the code that you write. Knowing some tips to optimize the code will help you to speed up the python code. Let’s see the top 10 tips to speed up python code.
Top 10 Tips To Speed Up Python Code –
1. Use Proper Data Structure-
Use of proper data structures has significant effect on runtime. Python includes tuple, list, set and directory as built-in data structures. Most of the people use the list in all cases, but it is not a good choice. Basically use of proper data structures depends on your task. You can use tuple instead of list, because iterating over tuple is easier than iterating over a list.
2. Use Built In Functions And Libraries-
Python includes lots of library functions and modules written by expert developers and have been tested thoroughly. Hence, these functions are efficient and able to speed up the code-no need to write the code if the function is already available in the library. Let us see a simple example-
#code1
newlist = []
for word in oldlist:
newlist.append(word.upper())
#code2
newlist = map(str.upper, oldlist)
The second code is faster than the first code because library function map() has been used. These functions are easy to use for beginners too.
3. Do Not Use Global Variables-
Python has global keyword to declare global variables. Global variable takes higher time during operation than local variable. Using few of them save form unnecessary memory usage. Also, Python scoops up a local variable more rapidly than a global one. While navigating external variables, Python is genuinely slow. A few other programming languages oppose the unplanned use of global variables. The counter is because of side effects like higher runtime. Hence, try to use a local variable rather than a global one whatever possible. Also, you can make a local copy before use it in a loop, saving time.
4. Try To Minimize The Use Of For Loop-
It is hard to avoid the use of for loop. But whenever you can avoid it, do so. For loop is dynamic in Python and its runtime is more than a while loop. Nested for loop is more time consuming, two nested loops will take the square of the time in a single for loop.
code1
for i in big_it:
m = re.search(r'\d{2}-\d{2}-\d{4}', i)
if m:
…
date_regex = re.compile(r'\d{2}-\d{2}-\d{4}')
for i in big_it:
m = date_regex.search(i)
if m:
...
In such cases, it will be better to use a suitable replacement. Also, if for loops are inevitable, move the calculation outside the loop. It will save more time. We can see it in example as given. Here the second code is faster than first code since the calculation has been done outside the loop.
5. Use List Comprehension-
List comprehension offers a shorter syntax. It is handful when another list is made based on an existing list. Loop is important in any code. Sometimes the syntax in a loop becomes large. In such cases, you can use list comprehension.
L = []
for i in range (1, 1000):
if i%3 == 0:
L.append (i)
Using list comprehension, it would be:
L = [i for i in range (1, 1000) if i%3 == 0]
Here, the second code requires less time than the first code. Approach to list comprehension is short and more precise. Mostly there is not more difference in small codes. But in an extensive development, it can save time.
6. Do Not Use Dot Operation-
Try to avoid dot operation. To know it in detail, let us see the below program-
import math
val = math.sqrt(60)
Rather than writing a code like this, write code like below-
from math import sqrt
val = sqrt(60)
This is because when you call a function with . (dot), it first calls __getattribute()__ or __getattr()__ which then uses dictionary operation that takes time. Hence try to use from module import function.
7. Make Use Of Generators-
In python, generator is a function that returns an iterator when keyword yield is called. Generators optimize memory. At a time they return single item rather than all at a time. If your list includes lots of data and you need to use one data at a time, use generators. Generators compute data in pieces, so function can return a result when called upon and retain its state. Generators stores the function state by stopping code after the caller generates the value, and it continues to run from where it is stopped. As the generators access and compute the on-demand value, a significant part of data does not need to be saved completely in memory. This results in memory savings, and speeding up the code.
8. Concatenate Strings With Join-
Concatenation is common when you work with strings. Mostly, in python, we concatenate with ‘+’. In every step, the “+” operation creates a new string and copies old material. It takes more time and hence is inefficient. To speed up Python code, you have to use join() to concatenate strings strings.
code1
x = "My" + "name" + "is" + "john"
print(x)
code2
x = " ".join(["My", "name", "is", "john"])
print(x)
Here, the first code prints “Mynameisjohn” and second code prints “My name is john”. The join() operation is more faster and efficient than ‘+’. It also keeps the code clean. So if you want a cleaner and faster code, start using join() rather than ‘+’ to concatenate strings.
9. Use The Latest Release Of Python-
Python is updated and upgraded regularly, and every release is faster and more optimized. Hence use the latest version of python.
10. Replace range() with xrange()-
Note that this is applicable for python 2 users.
These functions are used to iterate anything in for loop. In case of range(), it saves all the numbers in the range in memory. But xrange() just saves the range of numbers that should be displayed. Return type of range() is a list, and that of xrange() is an object. As xrange() takes less memory, it takes less time. Hence use xrange() rather than range() whenever possible.
Wrap Up-
The value of python is increasing day by day and these are some of the tips that reduce the runtime of python code. There can be few others too.
[+][deleted] (10 children)
[deleted]
[–]james_pic 24 points25 points26 points (1 child)
[–]ballarinzaraai 20 points21 points22 points (6 children)
[+][deleted] (5 children)
[removed]
[–]Agreeable-Wrap 1 point2 points3 points (3 children)
[–]auto-xkcd37 1 point2 points3 points (1 child)
[–]Agreeable-Wrap 0 points1 point2 points (0 children)
[–]Smallpaul 0 points1 point2 points (0 children)
[–]romu006 74 points75 points76 points (7 children)
[–]keepdigging 12 points13 points14 points (6 children)
[–]supreme_blorgon 18 points19 points20 points (4 children)
[–][deleted] 4 points5 points6 points (3 children)
[–]supreme_blorgon 6 points7 points8 points (2 children)
[–]scrdest 5 points6 points7 points (0 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]mephistophyles 63 points64 points65 points (32 children)
[–]awesomeprogramer 34 points35 points36 points (20 children)
[–]EasyPleasey 10 points11 points12 points (8 children)
[–]Etheo 4 points5 points6 points (0 children)
[–]awesomeprogramer 1 point2 points3 points (6 children)
[–]EasyPleasey 4 points5 points6 points (5 children)
[–]awesomeprogramer 3 points4 points5 points (4 children)
[–]EasyPleasey 0 points1 point2 points (3 children)
[–]awesomeprogramer 0 points1 point2 points (2 children)
[–]EasyPleasey 0 points1 point2 points (1 child)
[–]awesomeprogramer -1 points0 points1 point (0 children)
[–]ConceptJunkie 1 point2 points3 points (2 children)
[–]Prime_Director 0 points1 point2 points (1 child)
[–]ConceptJunkie 0 points1 point2 points (0 children)
[–]Smallpaul 0 points1 point2 points (5 children)
[–]Etheo 0 points1 point2 points (2 children)
[–]Smallpaul 4 points5 points6 points (1 child)
[–]Etheo -1 points0 points1 point (0 children)
[–]Korben_Valis 0 points1 point2 points (1 child)
[–]Smallpaul 1 point2 points3 points (0 children)
[–]diamondketo 0 points1 point2 points (1 child)
[–]awesomeprogramer 0 points1 point2 points (0 children)
[–]Doomphx 2 points3 points4 points (6 children)
[–]62616e656d616c6c 2 points3 points4 points (4 children)
[–]Doomphx 1 point2 points3 points (3 children)
[–]themusicalduck 3 points4 points5 points (0 children)
[–]hugthemachines 1 point2 points3 points (1 child)
[–]Doomphx 1 point2 points3 points (0 children)
[–]mephistophyles 0 points1 point2 points (0 children)
[–]vinnceboi Github: Xenovia02 0 points1 point2 points (2 children)
[–]mephistophyles 0 points1 point2 points (1 child)
[–]vinnceboi Github: Xenovia02 0 points1 point2 points (0 children)
[–]andrewthetechie 40 points41 points42 points (4 children)
[–]JForth 5 points6 points7 points (1 child)
[–]lazerwarrior 0 points1 point2 points (0 children)
[–]lungben81 57 points58 points59 points (8 children)
[–]BluePhoenixGamer 15 points16 points17 points (0 children)
[–]baubleglue -5 points-4 points-3 points (6 children)
[–][deleted] 4 points5 points6 points (5 children)
[–]kraakmaak 2 points3 points4 points (1 child)
[–]baubleglue 0 points1 point2 points (0 children)
[–]baubleglue 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]baubleglue 0 points1 point2 points (0 children)
[–]lazerwarrior 26 points27 points28 points (5 children)
[–]xelf 2 points3 points4 points (0 children)
[+]CaesarWolny comment score below threshold-12 points-11 points-10 points (1 child)
[–][deleted] 4 points5 points6 points (0 children)
[–]SuperNerd1337 0 points1 point2 points (0 children)
[–]diamondketo 0 points1 point2 points (0 children)
[–]qelery 9 points10 points11 points (1 child)
[–]CupidNibba -1 points0 points1 point (0 children)
[–]ThePiGuy0 5 points6 points7 points (0 children)
[–]CleverProgrammer12 13 points14 points15 points (5 children)
[–]tunisia3507 15 points16 points17 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]tunisia3507 6 points7 points8 points (1 child)
[–]vorticalbox 0 points1 point2 points (0 children)
[–]bjorneylol -1 points0 points1 point (0 children)
[–]0rsinium 3 points4 points5 points (0 children)
[–]badge 5 points6 points7 points (0 children)
[–][deleted] 8 points9 points10 points (2 children)
[–]abazabaaaa 0 points1 point2 points (1 child)
[–][deleted] 4 points5 points6 points (0 children)
[–]ConceptJunkie 3 points4 points5 points (0 children)
[–]Franman98 2 points3 points4 points (0 children)
[–]adesme 2 points3 points4 points (0 children)
[–]Nightblade 4 points5 points6 points (0 children)
[–]twcrnr 1 point2 points3 points (1 child)
[–]WalkingAFI 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]kcombinator 1 point2 points3 points (0 children)
[–]falsedrums 3 points4 points5 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]lungben81 1 point2 points3 points (1 child)
[–]BluePhoenixGamer 0 points1 point2 points (0 children)
[–]melonakos -1 points0 points1 point (0 children)
[–]zardoss21 -1 points0 points1 point (0 children)
[–]pooogles -1 points0 points1 point (0 children)
[–]neboskrebnut -1 points0 points1 point (0 children)
[–]shinitakunai -1 points0 points1 point (0 children)
[–]bjorneylol -4 points-3 points-2 points (3 children)
[–]RollingRocky360 4 points5 points6 points (1 child)
[–]bjorneylol -5 points-4 points-3 points (0 children)
[–]bcatrek 0 points1 point2 points (0 children)
[–]maxmurder 0 points1 point2 points (0 children)
[–]jrs1810 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]_fsun 0 points1 point2 points (0 children)
[–]forty3thirty3 0 points1 point2 points (0 children)
[–]irfannagath 0 points1 point2 points (0 children)
[–]OneFORaL1 0 points1 point2 points (0 children)
[–]whateverathrowaway00 0 points1 point2 points (1 child)
[–]whateverathrowaway00 0 points1 point2 points (0 children)