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:
| Parameter | Type | Description |
|---|---|---|
| LEGB | Resolution Rule | Local -> Enclosing -> Global -> Built-in lookup order. |
| lambda | Anonymous Function | Single-expression function without a def header. |
Ready-to-Run Code Example
Executable in CompilraRun 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 += 1Related Python Tutorials & Compiler
Python Functions (def): Arguments, *args, **kwargs & Return
Functions are organized, reusable blocks of code defined using the def keyword to perform a specific action.
Python Classes and Objects (OOP): __init__, Methods & self
Classes provide a means of bundling data and functionality together, creating blueprints for object instances.
Python Lists: Operations, Slicing, and Built-in Methods
Lists are ordered, mutable collections of items. They are one of the most versatile built-in data types in Python.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.