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.
