Course contentsShow
← Python
Lesson 162 of 1,0603. Functions and ModularizationFree lesson

Applying the LEGB Rule for Variable Resolution

You will master the order of operations Python uses to search for variable names across Local, Enclosing, Global, and Built-in scopes.

In this lesson, you will learn the exact order Python uses to find the value of a variable whenever you reference its name in your code.

When you ask Python to use a variable, it doesn't look everywhere at once. It follows a specific priority list known as the LEGB rule. Think of it like a search party that starts in your immediate workspace and slowly expands outward until it finds what it needs.

The LEGB Order

  1. Local (L): Python first looks inside the current function or code block. If the variable is defined there, it uses that value immediately.
  2. Enclosing (E): If it isn't found locally, Python checks any "outer" functions (if you have a function nested inside another).
  3. Global (G): If it still isn't found, Python checks the top level of your script or module—where you define variables outside of any functions.
  4. Built-in (B): Finally, if the name isn't found anywhere else, Python checks its own list of reserved keywords and functions (like print or len).

Putting it into Practice

Consider this example:

x = "Global"

def outer():
    x = "Enclosing"
    def inner():
        x = "Local"
        print(x)
    inner()

outer()

When print(x) executes inside inner(), Python follows the LEGB rule:

  • L: It checks inner() first. It finds x = "Local".
  • It stops searching immediately and prints Local. It doesn't care that there is also an "Enclosing" or "Global" version of x; the Local version wins the search.

If you were to remove the x = "Local" line from inner(), Python would fail to find x locally and would move to the Enclosing scope, finding "Enclosing". If that were also missing, it would move to the Global scope and print "Global". Understanding this hierarchy prevents bugs where you might accidentally overwrite a variable name or struggle to access the correct data in nested functions.

Key Takeaway: Python resolves variable names by searching in the order of Local, Enclosing, Global, and finally Built-in scopes, stopping as soon as the first match is found.