LEGB Rule (Scope Resolution)

Last Updated: 23 Nov 2025

The LEGB Rule tells Python how it searches for a variable when you use it. LEGB stands for:

  • L (Local) → Inside current function/block
  • E (Enclosing) → Inside outer function (for nested functions)
  • G (Global) → Defined at top-level of file
  • B (Built-in) → Python’s built-in names (len, sum, etc.)

Hinglish Tip 🗣:Aise samajh lo — Python variable dhoondhne ka raasta follow karta hai: Pehlā Local → phir Enclosing → phir Global → phir Built-in.

Local (L)

Local variables exist inside a function.

x = 10 # global

def func():
x = 5 # local
print(x)

func() # Output: 5

Python first checks inside func() for x. Mil gaya → wahi print karega.


Enclosing (E)

Variables inside outer function, used by inner function.

def outer():
x = 20 # enclosing

    def inner():
        print(x)  # uses enclosing x

    inner()

outer() # Output: 20

Global (G)

Variables defined outside all functions.

x = 100 # global

def func():
print(x)

func() # Output: 100

Built-in (B)

If variable not found in L, E, or G… Python checks built-ins.

Example using len, sum, max, etc.

print(len([1, 2, 3])) # Built-in function

💡 Overriding a Built-in (Bad Practice) You can override a built-in, but avoid this. len = 50 # overrides built-in len!


global Keyword

If you want to modify a global variable inside a function:

x = 10

def change():
global x
x = 99

change()
print(x) # Output: 99

Without global, Python creates a local x, not modifying global.


nonlocal Keyword (for Enclosing Scope)

Used inside nested functions to modify enclosing variable.

def outer():
x = 10

    def inner():
        nonlocal x
        x = 30

    inner()
    print(x)

outer() # Output: 30

Hinglish Tip 🗣:nonlocal nested function ke bahar wale function ka variable badalne deta hai.


Full LEGB Example

x = "global"

def outer():
x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()

outer()

# Output: local

Search order: Local → Enclosing → Global → Built-in