Course contentsShow
← Python
Lesson 108 of 1,0602. Control Flow and LogicFree lesson

Optimizing Loop Performance with Local Variables

Learners will improve execution speed by minimizing global variable lookups and utilizing local variable caching within high-frequency loop iterations.

In this lesson, you will learn how to speed up your code by caching global variables into local variables before starting a high-frequency loop.

Why Python Loops Need Help

When Python runs a loop, it has to look up every variable name you use inside the loop body. If a variable is stored in the global scope (outside your function or loop), Python has to search through a dictionary to find it every single time the loop repeats. If your loop runs thousands or millions of times, those tiny lookup times add up, slowing down your program significantly.

The Power of Local Caching

To make your loops run faster, you can create a "local" copy of a frequently used global variable. Because Python can access local variables (those defined inside the function or loop scope) much faster than global ones, caching the value once before the loop begins saves the computer from searching repeatedly.

Consider this example where we perform a math operation inside a loop:

import math

# A global variable
PI = 3.14159

def calculate_areas(radii):
    # Cache the global variable locally to speed up the loop
    local_pi = PI
    
    results = []
    for r in radii:
        # Using local_pi is faster than looking up PI globally
        results.append(local_pi * (r ** 2))
    return results

In the code above, if radii contains millions of items, local_pi ensures that Python doesn't have to look up the global PI variable on every iteration. Instead, it accesses the local local_pi instantly from its internal fast-access stack.

When to Use This

You don't need to do this for every small script! This technique is most effective when:

  1. You are working with very large datasets or long-running loops.
  2. You are accessing a global constant or a function from a module repeatedly within a tight loop.

By moving your dependencies into the local scope, you provide a performance boost that keeps your code efficient as it scales.

Key Takeaway: Moving global variables into local variables before starting a high-frequency loop minimizes lookup overhead, allowing your code to execute significantly faster.