13/20
Functions & Scope Β· Page 2 of 2

Lambda Functions & Scope

Lambda Functions

Small, anonymous functions defined in one line. Perfect for short operations.

# Normal function
def square(x): return x**2

# Lambda equivalent
square = lambda x: x**2

Where Lambdas shine: Inside functions like map(), filter(), and sorted():

names = ["Alice", "bob", "Charlie"]
sorted(names, key=lambda x: x.lower())

Variable Scope (LEGB Rule)

Python looks for variables in this order:

  1. Local (inside the function)
  2. Enclosing (inside nested functions)
  3. Global (module level)
  4. Built-in (Python built-ins like len, print)
x = "global"
def my_func():
    x = "local" # Creates a new local variable, doesn't change global
main.py
Loading...
OUTPUT
β–ΆClick "Run Code" to execute…