Python Mastery – From Basics to Brilliance / Functions

LEGB Rules

πŸ” LEGB Rule

The LEGB rule describes the order Python follows when looking for a variable or name.

LEGB stands for:

L β†’ Local
E β†’ Enclosing
G β†’ Global
B β†’ Built-in

Python searches for a name in this order:

Local β†’ Enclosing β†’ Global β†’ Built-in


1️⃣ Local

A variable created inside a function is local to that function.

def greet():
    name = "Tisha"
    print(name)

greet()

Here, name is a Local variable.

2️⃣ Enclosing

An enclosing variable is found in an outer function when there is a nested function.

def outer():
    name = "Tisha"
    def inner():
        print(name)
    inner()
outer()

Here, name is not inside inner(), so Python looks in the enclosing function outer().

3️⃣ Global

A variable created outside all functions is a global variable.

name = "Tisha"

def greet():
    print(name)

greet()

Python doesn't find name inside greet(), so it looks in the Global scope.

4️⃣ Built-in

If Python doesn't find the name in Local, Enclosing, or Global scope, it checks Python's built-in names.

Examples:

print()
len()
type()
sum()

These are available because they are built into Python.


🧩 Complete Example

name = "Global"

def outer():
    name = "Enclosing"

    def inner():
        name = "Local"
        print(name)

    inner()

outer() #Local

Python finds name immediately in the Local scope.

If we remove the local variable:

def outer():
    name = "Enclosing"

    def inner():
        print(name)

    inner()

outer() #Enclosing

Python then searches the Enclosing scope.