Lambda Functions: Anonymous One-Liners
A lambda function is a small, anonymous function defined without a name. It's used for small, simple tasks. It can take any number of arguments but can only have one expression.
python
Functions as First-Class Citizens
In Python, functions are objects! You can pass them as arguments to other functions like
map(), filter(), and sorted().python
Functional Programming: Map, Filter, Reduce
| Function | Action | Example |
|---|---|---|
| map(f, seq) | Apply f to all items | list(map(lambda x: x*2, [1, 2])) |
| filter(f, seq) | Keep items where f is True | list(filter(lambda x: x > 5, [2, 10])) |
python
Reduce: For summarizing a sequence into a single value, use
functools.reduce.python
Closures: Functions that Remember
A closure is a nested function that "remembers" the variables from its enclosing (outer) function, even after the outer function has finished executing.
python
Closures with State: nonlocal
Use
nonlocal to modify a variable from an outer function's scope.python
Wait! Should I use lambda or def?
- Use
def: For larger logic, reusability, and easier testing/debugging.- Use
lambda: For quick, throwaway functions as arguments (like insorted()ormap()).
Summary
| Feature | Description |
|---|---|
| Lambda | Anonymous, single-expression function |
| Sorted Key | Use lambda to customize sorting logic |
| Map/Filter | Apply/filter sequences without loops |
| Closure | Function with persistent outer-scope state |
| Nonlocal | Modify outer-scope variable from within a closure |
| Best For | Functional patterns, event handlers, factory logic |