TGViewer
Python Learning Python Learning @python_bds Β· 5.74K subscribers
Post #1144 1.02K
🧠 LEGB Rule in Python (Scope Resolution)

When Python looks for a variable, 
it follows a fixed order called LEGB.

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

Python searches in this order.


1️⃣ Local Scope (L) πŸ“ 
Variables defined inside a function.

x = 10

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

func()

Output:
5
➀ Python finds x inside the function first.


2️⃣ Enclosing Scope (E) πŸ”„ 
Variables in outer function (nested functions).

def outer():
    x = 20
    def inner():
        print(x)
    inner()

outer()

Output:
20
➀ Python finds x in the enclosing function.


3️⃣ Global Scope (G) 🌍 
Variables defined outside all functions.

x = 30

def func():
    print(x)

func()

Output:
30
➀ Python uses global x.


4️⃣ Built-in Scope (B) βš™οΈ 
Predefined names like len, print, etc.

print(len([1, 2, 3]))

Output:
3

πŸ’‘ Search Order

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

Python stops searching once it finds the name.
  • ❀ 3
More from @python_bds
  1. Oct 8, 2026πŸ› This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  2. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  3. Oct 4, 2026Python Set Methods ✍️
  4. Oct 3, 2026Post #1310
  5. Oct 1, 2026🐍 Python Beginner Notes
  6. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’