What is the LEGB rule in Python?
LEGB is the order in which Python looks up a name: Local, Enclosing (outer functions), Global (module), then Built-in. The first scope that contains the name wins, and if none do, Python raises NameError.
Explain it simply
You are looking for a pen. First check your own pocket (Local), then your friend's bag if you are sitting in their room (Enclosing), then the classroom shelf (Global), and finally the college store (Built-in). You stop at the first place where you find one.
Example
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # Output: local
inner()
print(x) # Output: enclosing
outer()
print(x) # Output: global
def shadow():
print(len([1, 2])) # Output: 2
shadow()len is not defined by you at all, so Python finds it in the built-in scope. If you wrote len = 5 at module level, it would shadow the built-in len.
What to say in the interview
"Python resolves a name by searching the local scope, then any enclosing function scopes, then the module's global scope, then built-ins. Assignment inside a function creates a local name by default; global or nonlocal change that. Shadowing built-ins like list or sum is a common bug."
Common mistakes
- Naming a variable
list,strormaxand later wondering why the built-in stops working.