Python7 min read

Python Performance Optimization

Optimize Python code for better performance.

David Miller
December 18, 2025
0.0k0

Make Python code faster.

Use Built-in Functions

```python # Slow total = 0 for i in range(1000): total += i

Fast total = sum(range(1000)) ```

List Comprehension vs Loop

```python # Slower squares = [] for i in range(1000): squares.append(i ** 2)

Faster squares = [i ** 2 for i in range(1000)] ```

Use Local Variables

```python import math

Slow - looks up math.sqrt each time def slow(): for i in range(1000): result = math.sqrt(i)

Fast - local variable def fast(): sqrt = math.sqrt for i in range(1000): result = sqrt(i) ```

Avoid Global Variables

```python # Slow counter = 0 def slow_count(): global counter for i in range(1000): counter += 1

Fast def fast_count(): counter = 0 for i in range(1000): counter += 1 return counter ```

Use Sets for Membership

```python # Slow - O(n) items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if 5 in items: pass

Fast - O(1) items = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} if 5 in items: pass ```

Profile Your Code

```python import cProfile

def my_function(): result = sum([i ** 2 for i in range(10000)]) return result

cProfile.run('my_function()') ```

Use NumPy for Numbers

```python import numpy as np

Much faster for numerical operations arr = np.array([1, 2, 3, 4, 5]) result = arr * 2 ```

Remember

- Profile before optimizing - Use built-in functions - List comprehensions are fast - Sets for membership tests

#Python#Advanced#Performance