Python › Functions & Scope

What is Python's LEGB rule for variable scope resolution, and what does each letter stand for?

Intermediate

Answer

LEGB describes the order Python searches for a variable name: Local (the current function), Enclosing (any outer function, for closures), Global (the module level), and Built-in (Python's built-in names like len or print) — Python looks in each scope in that order and uses the FIRST match found.
x = "global"
def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)  # 'local' -- found in Local scope first
    inner()
outer()
Real-world example Understanding exactly which 'x' a function refers to when the same name exists at multiple scope levels.

Common follow-ups: What happens if a variable name isn't found in ANY of the four LEGB scopes?