Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the LEGB rule in Python?

SHORT ANSWER

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

python
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, str or max and later wondering why the built-in stops working.

#python#functions#scope

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.