Make Your Python Code Faster

Riya Jain
Geek Culture
Published in
4 min readDec 30, 2020

--

Python is a slow language

I’m sure you heard a lot of people complaining that Python is so slow. I see people compare Python to C in the context of performance only, but they don’t compare in the context of fast development.

It is a dynamically-typed language meaning its variable types are not predefined, although, this is a double-edged sword as being dynamically-typed is what makes Python such an elegant language. So Python is a slower language to run, but faster to type.

Let’s look at some minor tips that could have a major impact on your overall code performance in the long run.

1. A, B = B, A

I’m sure you’ve used “temp” before as a placeholder variable to swap two elements. What I can tell you is that method belongs in the classroom, and it should not be used when you’re coding.

Instead opt for a simple swap of variables by writing them in a,b = b,a order. This switches your variables all in one line and prevents the interpreter from going over three(temp, a,b swap method).

This is a tiny fix that saves fractions of a second — but fractions add up in the long run.

2. Go For Sets Instead Of Lists

This is one of the oldest tricks in the Python book of optimizations. Do not go searching in your list if an element exists. Instead, make the list a set (set(list)) and then do your check “ element in set(list) ”. This minor change will improve your runtime efficiency because the lookup in a set is O(1) vs O(n) in a list.

However, iterating through a set is not faster than iterating through a list.

3. List Comprehensions

In Python, a great syntax that is computationally more efficient for creating lists than a loop is list comprehensions. So if you need to, say, have a list of squares of first 10 positive integers, instead of:

squares = []
for i in range (10):
squares.append(i ** 2)

You can do:

squares = [i ** 2 for i in range(10)]

You can try and compare which implementation runs faster using, for example, the timeit module.

You can also have nested list comprehensions just like nested loops but it is normally discouraged, precisely because it makes the code more difficult to read, maintain, and test.

4. Import Within The Functions

As a beginner, we all like to mass import everything we think we will need at the top of our code. I remember one-time importing NumPy, Pandas, Math, Os, etc, and by the time I was finished with my code I only used three libraries. This eats up the memory of your computer.

Instead, import the needed library within its corresponding function (import multiple times if multiple functions need the same library). This means the interpreter will only complete the import when you call the function rather than at the beginning of the code.

Python libraries are cached so no it does not take up extra time with each import when you call a different function. However, it does take up more time when you end up importing everything at the top and not even using some of the functions of your code.

5. Know The Built-In Functions

When I was beginning Python, I used to never use built-in functions, so to complete my absolute value code I would run a for loop instead of use abs(). To change a character to uppercase, I would even convert it to the ASCII equivalent of the uppercase letter because I refused to learn string functions.

If you’re serious about Python it is worth it to actually study all the built-in Python functions because not only does it make your code neater and more reusable, you can also avoid tiny human inefficiencies in your code by simply using what Python gives you.

6. Avoid unnecessary functions

A good example of an approach that can help save a significant amount of the runtime complexity but requires a lot of careful thought is function calls. While you do want the nice abstraction, extensibility, and re-usability that functions provide, you might not want to have a function for every single thing, because function calls are quite expensive in Python (if you’re interested, there are interesting observations on that in this article).

So sometimes, you might want to sacrifice, for example, writing a getter and/or a setter. On the other hand, fewer functions make the code less testable. So the final decision really depends on the specifics of your application.

7. Avoid the dot

If you have an object and you are using some of its properties, assign them to local variables first:

rectangle_height = rectangle.height
rectangle_width = rectangle.width

So if later in your code you’re computing, for instance, its surface, you will do:

surface = rectangle_height * rectangle_width

And if later you also compute its perimeter, you will re-use the same variables:

perimeter = 2 * rectangle_height + 2 * rectangle_width

For the same reasons, using globals is often discouraged — you don’t want to be wasting time looking up, first, the global variable itself, and then each of its properties you may be referencing.

That’s all for this blog. I hope all the tips mentioned above will help you optimize the code better. Happy Coding!

--

--

Riya Jain
Geek Culture

I am a B.Tech. Undergrad and loves programming. Scholar at Google Women Techmakers and currently exploring different tech fields.