As a popular dynamic programming language, Python appeals to developers thanks to its simplicity, vast ecosystem of libraries, and overall versatility. However, one common complaint is that Python code tends to run slower compared to statically-typed languages like C and Java.
While execution speed may not matter for some scripts, it becomes critical in data or computationally intensive applications. The good news is there are small tweaks any Python developer can make to significantly speed up their code. In this post I’ll share 5 easy ways to boost your Python program’s performance.
1. Use Generators Instead of Returning Lists
A common Python pattern is to iterate through a list returned by a function. This forces the creation of the entire list in memory even when we only want to iterate through it once. Generators allow us to lazily yield one item at a time instead of materializing an entire list:
# Without generator
def get_squares_list(nums):
squares = []
for n in nums:
squares.append(n * n)
return squares
# With generator
def get_squares_generator(nums):
for n in nums:
yield n * n