DEV Community

Cover image for How to speed up your python program….. with basics
Sahithi Reddy
Sahithi Reddy

Posted on

How to speed up your python program….. with basics

Some people are inappropriately obsessed with python like me. Here, are some guidelines you can use them in daily coding.

  • String concatenation is best done with ''.join(list) which is an O(n) process. In contrast, using the '+' or '+=' operators can result in an O(n**2).

  • Use built-in functions
    (https://www.w3schools.com/python/python_ref_functions.asp) to avoid loops and used these functions like set(): to identify duplicates, del: to delete/remove multiple items for a list/array(eg: del arr[2:5]).

  • In functions, local variables are accessed more quickly than global variables.

  • If the body of your loop is simple, try to use map(), filter() or reduce() to replace an explicit for loop.

  • List comprehensions run a bit faster than equivalent for-loops. Avoid inside loop, write "x=3" instead of "x=1+2".

  • While using FOR loops and conditions(if/else), use "break" to come out of the loop.

  • Use numpy and pandas to convert large data into small chucks. Therefore, load in small chunks, process the chunk of data, and save the result is one of the most useful techniques to prevent memory error.

  • Multiple assignment is slower than individual assignment. For example "x,y=a,b" is slower than "x=a; y=b". However, multiple assignment is faster for variable swaps. For example, "x,y=y,x" is faster than "t=x; x=y; y=t".

  • Chained comparisons are faster than using the "and" operator. Write "x < y < z" instead of "x < y and y < z".

  • At last, always try to write less time complexity code.

Top comments (0)