QA
Beginner LevelPython

What is the LEGB scope resolution rule (Local, Enclosing, Global, Built-in) and when do you use global vs nonlocal?

❓ Interview Prompt: Explain LEGB scope lookup order, `global` keyword (modifying module-level vars), and `nonlocal` keyword (modifying outer closure vars).

Python resolves variable names using the LEGB Rule order:

1
Local: Names assigned inside current function.
2
Enclosing: Names in outer enclosing functions (closures).
3
Global: Names assigned at module top-level.
4
Built-in: Predefined built-in names ('len', 'range').

'global' vs 'nonlocal':

•
'global var': Grants write permission to modify module-level global variables.
•
'nonlocal var': Grants write permission to modify variables in enclosing nested closures!

Code Implementation Example

python
x = 'global'

def outer():
    x = 'enclosing'
    def inner():
        nonlocal x # Modifies outer's 'x' variable!
        x = 'modified_enclosing'
    inner()
    print('Outer x:', x)

outer() # Prints: Outer x: modified_enclosing
💡Modifying enclosing scope variables inside closures using nonlocal.
🎯 Interview Key Takeaway

Use 'nonlocal' to modify outer variables inside closures, and 'global' for top-level module variables.

#LEGB Scope#global#nonlocal#Closures#Beginner
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?