Lambda & Functional ToolsAdvanced
1Question 1 of 1
pythonHow do Lambda functions and the functools module work in Python?
Explanation & Concept
• `lambda`: Anonymous inline functions for simple expressions: `lambda x: x * 2`. • `functools`: Standard module with utilities like `partial` (pre-fill arguments), `reduce` (fold iterable), and `@lru_cache` (memoization).
Code Example
python
from functools import lru_cache, partial
# 1. Memoized recursive function with LRU cache
@lru_cache(maxsize=128)
def fib(n: int) -> int:
if n < 2: return n
return fib(n - 1) + fib(n - 2)
# 2. Partial application
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # 25How It Works & Key Takeaways
`@lru_cache` caches expensive function outputs in memory, reducing exponential O(2^N) recursion to linear O(N) performance.
Mock Test · 1 Questions · Optional
Ready for Magic/Dunder Methods?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions