10 Simple Ways To Speed Up Your Python Code

Why should you care about your Python code performance?

Let's be honest first, you're not using Python in your project because it's a fast programming language, but because it's easy for you to translate your idea into real life working product. So from the beginning, speed is not a problem for you, so why should you even bother to spend your precious time upgrading it? For me, writting code is not just putting sloppy working pieces together and then call it a day. I want to learn more about how to write faster, cleaner and simpler code. Because of this, I've been looking around for ways to increase my Python code's performanc ewithout sacrificing its readability. Let me show you the way of the force!

1. Choose wisely between "Ask for Forgiveness" and "Look before you leap"

try: with open("path/to/file.txt", "r") as fp: return fp.read() except IOError: # Handle the error or just ignore it 
Enter fullscreen mode

Exit fullscreen mode

# Check if file exists and if we have the permission to read it if Path("/path/to/file").exists() and os.access("path/to/file.txt", os.R_OK): with open("path/to/file.txt") as input_file: return input_file.read() 
Enter fullscreen mode

Exit fullscreen mode

2. How to properly filter a list:

There are 3 popular ways to filter a list in Python:

# Get all even numbers in the list contains 1 million number def filter_odd_number(): lst = list(range(1000000)) res = [] for item in lst: if item % 2 == 0: res.append(item) return res 
Enter fullscreen mode

Exit fullscreen mode

def filter_odd_number(): lst = list(range(1000000)) return [item for item in lst if item % 2 == 0] 
Enter fullscreen mode

Exit fullscreen mode

def filter_odd_number(): lst = list(range(1000000)) return filter(lambda x: x % 2 == 0, lst) 
Enter fullscreen mode

Exit fullscreen mode

3. Checking for True or False

We have 3 ways to achieve this:

Wait, it's not going to be that easy. In Python, there's a concept called "truthy & falsy", it means that there are variables interpreted as True or False if you run bool(variable) (explicitly by you or by the interpreter when you put them behind the if clause). Now, you may have different logic to deal with a certain type of the data.

var = [] # or None or True if len(var) == 0: print("empty") elif var is None: print("null") elif var is True: print(true) 
Enter fullscreen mode

Exit fullscreen mode

4. Use in to check if item exists in a collections of item

5. Remove duplicate value inside a list

There should be many ways to implement this task, but 3 stand out the most:

6. Declare a data structure in style

When you need to declare an empty list , dict , tuple or set , you should use the Pythonista syntax rather than explicitly call the function because it will be faster and shorter to (~100% faster). This is because when you call the function, Python would then try to check if there's any other function with that name in your script before thinking about using its own

7. String format

Python 3.6 introduce the famous f-string for us to build formated string (before that we have to use the .format() or Template string) and since then it's hard to find someone who doesn't love them! But is it the optimal way to create a format string?

name, age = "Triet", 24 s = f"My name is name>, I'm age> years old" 
Enter fullscreen mode

Exit fullscreen mode

8. Map vs List Comprehension

In the previous section, I've said that you should always use "List comprehension" instead of for loop for tasks that require you to loop over a list. One big problem with that is "List comprehension" cannot take too many logic inside (without ruin your beautiful code), so my solution back there is to wrap that logic into a function, then call it inside of the "List comprehension". It's a good work around, But should you do it?

def pow2(x): return x**2 arr = list(range(1000000)) res = list(map(pow2, arr)) 
Enter fullscreen mode

Exit fullscreen mode

Why we need the list() outside of map() you asked? Well map() return a generator which would return item one by one when you call it, so list should get the whole result and put them back inside a list

9. Inlining Functions

def inline_functions(): return sum([sum([sum([1 for _ in range(100)]) for _ in range(100)]) for _ in range(100)]) 
Enter fullscreen mode

Exit fullscreen mode

I've won. But at what cost?

10. Upgrade your Python version

Reference