Python:Python Variable Scope (LEGB Rule) and Lambda Functions
Python•Scope & Lambdas

Python Variable Scope (LEGB Rule) and Lambda Functions

Python determines variable visibility based on lexical hierarchy. Anonymous functions (lambdas) provide concise one-line callable expressions.

Syntax

global_var = 100 lambda x, y: x + y

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
LEGBResolution RuleLocal -> Enclosing -> Global -> Built-in lookup order.
lambdaAnonymous FunctionSingle-expression function without a def header.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# 1. LEGB Scope Demonstration
global_counter = 10

def outer_function():
    enclosing_val = "Enclosing"
    def inner_function():
        local_val = "Local"
        print(f"Scopes: {local_val} -> {enclosing_val} -> {global_counter}")
    inner_function()

outer_function()

# 2. Lambda Functions with sorted()
products = [("Laptop", 1200), ("Mouse", 25), ("Monitor", 300)]
# Sort by price ascending using lambda key
sorted_by_price = sorted(products, key=lambda item: item[1])
print(f"\nSorted by price: {sorted_by_price}")
Expected Output:
Scopes: Local -> Enclosing -> 10

Sorted by price: [('Mouse', 25), ('Monitor', 300), ('Laptop', 1200)]

How It Works: Step-by-Step

  • Lines 4-10: Demonstrates nested closures referencing outer variables.
  • Lines 14-16: Applies lambda item: item[1] to sort tuples by their second element.

Key Concepts

  • Python looks up names hierarchically: Local, Enclosing function, Global module, Built-in.
  • To modify a global variable inside a function, use the global keyword.
  • Lambdas are syntactically restricted to a single expression and return its value automatically.

Common Mistake: Trying to modify an outer variable without global or nonlocal keyword

Assigning to a variable inside a function creates a new local variable by default.

❌ Incorrect
count = 0
def bump():
    count += 1 # UnboundLocalError: local variable referenced before assignment
✅ Correct
count = 0
def bump():
    global count
    count += 1

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler