λ Functional Programming in Python
Python is a multi-paradigm language that supports functional programming (FP) concepts. FP treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
🧩 Lambda Functions
Anonymous, small functions defined with lambda.
add = lambda x, y: x + y
print(add(2, 3)) # 5
🗺 Map, Filter, Reduce
Classic FP tools.
Map
Applies a function to all items in an input list.
items = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, items))
# [1, 4, 9, 16]
Filter
Creates a list of elements for which a function returns true.
items = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, items))
# [2, 4]
Reduce
Performs a rolling computation to sequential pairs of values.
from functools import reduce
items = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, items)
# 24
🧊 Immutability
Python doesn't enforce immutability, but you can use tuples and frozenset to prevent modification.
t = (1, 2, 3)
# t[0] = 5 # TypeError
🧩 Partials
functools.partial allows you to fix a certain number of arguments of a function and generate a new function.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(5)) # 125
📝 Summary
- ✅ First-Class Functions: Functions can be passed as arguments.
- ✅ Lambda: Inline functions.
- ✅ Map/Filter/Reduce: Process collections without loops.
- ✅ List Comprehensions: often more Pythonic than map/filter.
Created with ❤️ by Pynfinity