Page13/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:
- Local (inside the function)
- Enclosing (inside nested functions)
- Global (module level)
- 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β¦