Introduction to Functional Programming in Python
This article introduces Python's functional programming features, covering first‑class functions, callable objects, storing functions in data structures, higher‑order functions, nested functions, lambda expressions, and the use of map, filter, and reduce with clear code examples.
Python treats functions as first‑class citizens, meaning they can be assigned to variables, passed as arguments, stored in containers, and returned from other functions. For example:
def foo():
print("foo")Assigning a function to a variable and calling it works the same as calling the original function:
bar = foo
bar()
# will print "foo" to the consoleObjects can be made callable by defining a __call__ method. The following class demonstrates a callable greeter:
class Greeter:
def __init__(self, greeting):
self.greeting = greeting
def __call__(self, name):
return self.greeting + " " + name
morning = Greeter("good morning")
morning("john") # prints "good morning john"Functions can also be stored in data structures such as dictionaries and invoked dynamically:
mapping = {0: foo, 1: bar}
# get an integer from the user
x = input()
mapping[int(x)]() # calls the selected functionHigher‑order functions accept other functions as parameters or return them. An iterate_custom example shows how to apply a custom function to each item in a list:
def iterate_custom(list_of_items, custom_func):
for item in list_of_items:
custom_func(item)Nested (inner) functions enable helper functions that are scoped to a parent function, as illustrated by a recursive Fibonacci implementation using an inner helper:
def fib(n):
def fib_helper(fk1, fk, k):
if n == k:
return fk
else:
return fib_helper(fk, fk1 + fk, k + 1)
if n <= 1:
return n
else:
return fib_helper(0, 1, 1)Lambda expressions provide a concise way to define anonymous single‑line functions. For instance:
mult = lambda x, y: x * y
mult(1, 2) # returns 2Lambda functions are often used with map , filter , and reduce to process collections:
# map example
scores = [3, 6, 8, 3, 5, 7]
modified_scores = list(map(lambda x: 4 * x, scores))
# filter example
even_scores = list(filter(lambda x: True if (x % 2 == 0) else False, scores))
# reduce example
from functools import reduce
sum_scores = reduce(lambda x, y: x + y, scores) # sum_scores == 32These functional constructs allow more abstract, reusable, and expressive code compared to traditional imperative loops.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.