Lesson 13: Functional Programming Features in Python
Python, while primarily known as an imperative and object-oriented language, fully supports functional programming (FP) paradigms. In this lesson, we explore several key functional programming features available in Python.
Higher-Order Functions
Higher-order functions are functions that take other functions as arguments or return them as results. This feature is central to functional programming.
def apply_twice(func, arg):
return func(func(arg))
def add_five(x):
return x + 5
result = apply_twice(add_five, 10)
print(result) # Output: 20
Lambda Expressions
Lambda expressions provide a compact way to create anonymous functions. These are often used with higher-order functions.
double = lambda x: x * 2
print(double(5)) # Output: 10
Map, Filter, and Reduce
The map
, filter
, and reduce
functions are powerful tools for functional transformations of data collections.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Map
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4]
# Reduce
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers) # Output: 15
Immutability
Functional programming emphasizes the use of immutable data structures. Python's tuple
provides a simple way to create immutable data.
point = (10, 20)
# Attempting to change a value will result in an error
try:
point[0] = 30
except TypeError as e:
print(e) # Output: 'tuple' object does not support item assignment
Functional Libraries in Python
Python's standard library includes several modules that facilitate functional programming. Notably, the itertools
and functools
modules provide tools for working with iterators, higher-order functions, and other functional programming constructs.
Example: Using itertools
from itertools import permutations
data = [1, 2, 3]
perms = list(permutations(data))
print(perms)
Example: Using functools
from functools import partial
def multiply(x, y):
return x * y
# Create a new function that multiplies by 2
double = partial(multiply, 2)
print(double(5)) # Output: 10
graph LR
A["map"] --> B["lambda"]
C["filter"] --> D["lambda"]
E["reduce"] --> F["lambda"]
Continue learning about functional programming in Python by checking out our next lesson: Writing Pure Functions in Python.
For more background on functional programming, visit our article on What is Functional Programming?.