Functional Programming

Python AdvancedParadigmsFree Lesson

Advertisement

Introduction

Functional programming emphasizes immutability, pure functions, and higher-order functions. Python supports FP concepts through first-class functions and built-in tools.

Immutability

from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float

def move_point(p: Point, dx: float, dy: float) -> Point:
    return Point(p.x + dx, p.y + dy)

p1 = Point(1, 2)
p2 = move_point(p1, 3, 4)
print(p1)  # Point(x=1, y=2) - unchanged
print(p2)  # Point(x=4, y=6)

Pure Functions

# Pure function - no side effects, same input = same output
def add(a: int, b: int) -> int:
    return a + b

# Impure function - side effects
total = 0

def add_to_global(n):
    global total
    total += n
    return total

Higher-Order Functions

from functools import partial

def apply_operation(x, operation):
    return operation(x)

def double(x):
    return x * 2

def square(x):
    return x ** 2

result = apply_operation(5, double)  # 10
result = apply_operation(5, square)  # 25

# Using partial
multiply_by_3 = partial(lambda x, y: x * y, 3)
print(multiply_by_3(10))  # 30

Function Composition

def compose(f, g):
    return lambda x: f(g(x))

def add_one(x):
    return x + 1

def double(x):
    return x * 2

add_one_then_double = compose(double, add_one)
print(add_one_then_double(5))  # 12

Lambda Functions

# Lambda for simple transformations
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))

filtered = list(filter(lambda x: x > 2, numbers))

pairs = [(1, "one"), (2, "two"), (3, "three")]
sorted_pairs = sorted(pairs, key=lambda p: p[1])

Practice Problems

  1. Create immutable data structures
  2. Write pure function for list processing
  3. Implement higher-order function
  4. Create function composition utility
  5. Use lambda with map/filter/reduce

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement