nextRound
TechnologiesCoding ProblemsBookmarksLearning PathsLogin
nextRound
TechnologiesCoding ProblemsBookmarksLearning PathsLogin
nextRound

AI-powered interview preparation platform. Practice with curated questions, mock interviews, and personalized learning paths to crack your dream tech interview.

Quick Links

  • Technologies
  • Mock Interviews
  • Saved Questions
  • Pricing

Company

  • About Us
  • Contact Us

Legal

  • Privacy Policy
  • Terms of Use

© 2026 nextRound. All rights reserved.

Questions
9 of 18
1Why is using a mutable default argument (e.g., `def f(x=[])`) considered a common pitfall?
2What is the purpose of the `nonlocal` keyword, and how does it differ from `global`?
3How does Python's `for` loop differ conceptually from a C-style `for` loop?
4How does structural pattern matching (`match`/`case`, introduced in Python 3.10) differ from a chain of `if`/`elif` statements?
5What are first-class functions, and how does Python's treatment of functions as objects enable higher-order functions?
6What is the purpose of the `else` clause on `for` and `while` loops, and when does it execute?
7How would you implement memoization for a recursive function, and what tradeoffs exist between manual caching and `functools.lru_cache`?
8What is the difference between positional, keyword, default, `*args`, and `**kwargs` parameters?
9Explain Python's LEGB rule for variable scope resolution.
10How does Python's `for` loop differ conceptually from a C-style `for` loop?
11What are first-class functions, and how does Python's treatment of functions as objects enable higher-order functions?
12How would you implement memoization for a recursive function, and what tradeoffs exist between manual caching and `functools.lru_cache`?
13What is the purpose of the `nonlocal` keyword, and how does it differ from `global`?
14What is the difference between positional, keyword, default, `*args`, and `**kwargs` parameters?
15Why is using a mutable default argument (e.g., `def f(x=[])`) considered a common pitfall?
16How does structural pattern matching (`match`/`case`, introduced in Python 3.10) differ from a chain of `if`/`elif` statements?
17What is the purpose of the `else` clause on `for` and `while` loops, and when does it execute?
18Explain Python's LEGB rule for variable scope resolution.
PythonPython
Basics
Control Flow and Functions
Data Structures
Comprehensions & Functional Programming
Iterators, Generators & Decorators
Object-Oriented Programming
Exception Handling & Debugging
Concurrency & Parallelism
Performance & Optimization
Testing
Security
Modules, Packaging & Environment
Type Hinting & Modern Python
System Design & Architecture with Python
Best Practices & Design Patterns
Edge Cases & Tricky Interview Questions
09 / 18

Explain Python's LEGB rule for variable scope resolution.

Difficulty: 5/10
Functions & Scope, Variable Scope, Closures and Late Binding

LEGB: Local, Enclosing, Global, Built-in

When Python looks up a bare name it searches four scopes in order: Local (the current function), Enclosing (any outer function scopes, innermost first), Global (the module's namespace), and Built-in (the builtins module, which supplies len, print, list and so on). The first match wins and the search stops. Only functions, modules, classes (with special rules), lambdas and, until 3.12, comprehensions create scopes; if, for, while, try and with blocks do not.

javascript

The key insight, and what separates a good answer: scope is decided at compile time, per function, by looking at where a name is assigned. If a function assigns to a name anywhere (including +=, for targets, import, and def), that name is local throughout the function. That is why reading it before assignment raises UnboundLocalError rather than falling back to the global value. To rebind a global or an enclosing variable you declare global or nonlocal; to merely read or mutate an object you do not need either.

Details worth knowing: names are resolved at call time, which gives rise to the late-binding closure behavior in the example; class bodies have their own namespace that nested functions and methods do not see as an enclosing scope (so a method must use self.attr or ClassName.attr); and an exception variable in except E as e is deleted at the end of the except block. Comprehensions had their own function-like scope in Python 3, and in 3.12 PEP 709 inlined them for speed while preserving the isolation semantics, so the observable behavior is the same.

Common mistakes: shadowing built-ins (list, dict, id, type, input) and later wondering why they stopped working; relying on module-level mutable globals, which complicates testing and concurrency (prefer passing parameters, dependency injection or contextvars); and assuming loops introduce a scope, so the loop variable leaks. At the bytecode level the rules appear as LOAD_FAST, LOAD_DEREF, LOAD_GLOBAL and LOAD_NAME.

Scenario Questions

0-2 years experience

  1. 1Predict the output: x = 'global'; def f(): x = 'local'; print(x); then call f() and print(x). Explain which scope each x comes from.
  2. 2Why can you call len() and print() without importing them, and what happens if you name a variable list?

2-5 years experience

  1. 1Why does count += 1 inside a function raise UnboundLocalError when count is a module-level variable, and how can you fix it?
  2. 2Do if blocks and for loops create a new scope? What about comprehensions? Give examples that show the difference.

5-8 years experience

  1. 1Lambdas created in a loop all return the last value. Explain it with LEGB and late binding, and give at least two fixes.
  2. 2Why can't a method reference a class attribute by its bare name, and why might a comprehension inside a class body fail to see class variables?

8+ years experience

  1. 1How does the compiler decide scope (symbol tables, LOAD_FAST, LOAD_DEREF, LOAD_GLOBAL, LOAD_NAME), and what did PEP 709 (inlined comprehensions in 3.12) change?
  2. 2A large application depends on module-level mutable globals. How does that hurt testing and concurrency, and what patterns (dependency injection, contextvars) would you introduce?

Follow-up Questions

  • Why does a closure created in a loop capture the variable rather than its value at the time?
  • Why can't a method refer to a class attribute by its bare name?
Sharethis question

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.