Menu
Courses / python advanced / Functional Programming

Functional Programming

07 / 10 Part of python advanced




 

    🎓 Advanced · Topic 07
 

 


    Functional Programming
 


 


    Write cleaner, more predictable code using pure functions, immutability, closures, partial application, and the powerful tools in functools and itertools.
 


 

    ⏱ ~55 min
    🔴 Advanced
    🧮 Paradigm
 


 
 

   

     
     

Pure Functions & Immutability


   

   

A pure function always returns the same output for the same input and has no side effects. This makes code trivial to test and reason about.


   

     

        pure_functions.py
     

     
# ❌ Impure — mutates its argument
def add_item_bad(lst, item):
    lst.append(item)
    return lst

# ✅ Pure — returns a new list
def add_item(lst, item):
    return [*lst, item]

original = [1, 2, 3]
new_list = add_item(original, 4)
print(original)   # [1, 2, 3] — unchanged
print(new_list)   # [1, 2, 3, 4]

   

 


 
 

   

     
     

map, filter, and reduce


   

   

The classic functional trio for transforming sequences. In Python, list comprehensions are often preferred, but these shine when composing pipelines.


   

     

        map_filter_reduce.py
     

     
from functools import reduce

nums = [1, 2, 3, 4, 5]

squares  = list(map(lambda x: x**2, nums))
print(squares)   # [1, 4, 9, 16, 25]

evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)     # [2, 4]

product = reduce(lambda a, b: a * b, nums)
print(product)   # 120  (1×2×3×4×5)

   

 


 
 

   

     
     

functools Toolkit


   

   

     

        functools_tools.py
     

     
from functools import partial, lru_cache, cache

# partial — pre-fill arguments
def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube   = partial(power, exp=3)
print(square(5), cube(3))  # 25 27

# lru_cache — memoize expensive calls
@lru_cache(maxsize=128)
def fib(n: int) -> int:
    return n if n < 2 else fib(n-1) + fib(n-2)

print(fib(50))   # instant — without cache: 2^50 calls
print(fib.cache_info())

   

 


 
 

   

     
     

itertools — Lazy Sequence Combinators


   

   

The itertools module provides composable, memory-efficient building blocks for working with iterables.


   

     

        itertools_examples.py
     

     
import itertools

# chain — flatten multiple iterables
combined = list(itertools.chain([1,2], [3,4], [5]))
print(combined)   # [1, 2, 3, 4, 5]

# islice — lazy slice of any iterable
first_5 = list(itertools.islice(itertools.count(10), 5))
print(first_5)    # [10, 11, 12, 13, 14]

# groupby — group sorted data
data = [("a",1),("a",2),("b",3)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
    print(key, list(group))

# combinations & permutations
print(list(itertools.combinations("ABC", 2)))
# [('A','B'), ('A','C'), ('B','C')]