Introduction to Functional Programming in Python
This article introduces functional programming techniques in Python, covering first‑class functions, treating functions as objects, higher‑order functions, lambda expressions, and built‑in utilities like map, filter, and reduce, with clear code examples and explanations of their practical uses.
Python treats functions as first‑class citizens, meaning they can be assigned to variables, passed as arguments, stored in data structures, and returned from other functions.
Example of assigning a function to a variable:
<code>def foo():
print('foo')
bar = foo
bar() # will print 'foo' to the console</code>Objects can be made callable by defining a __call__ method. The following class demonstrates a callable object:
<code>class Greeter:
def __init__(self, greeting):
self.greeting = greeting
def __call__(self, name):
return self.greeting + ' ' + name
morning = Greeter('good morning')
print(morning('john')) # prints 'good morning john'</code>Functions can also be stored in data structures such as dictionaries:
<code># store in dictionary
mapping = {
0: foo,
1: bar
}
x = input() # get integer value from user
mapping[int(x)]() # call the selected function</code>Higher‑order functions accept other functions as parameters or return them. For example, a custom iterator can apply any function to each item in a list:
<code>def iterate_custom(list_of_items, custom_func):
for item in list_of_items:
custom_func(item)</code>Using higher‑order functions, we can build a simple calculator that returns different operation functions based on an opcode:
<code>def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def calculator(opcode):
if opcode == 1:
return add
elif opcode == 2:
return sub
else:
return mult
my_calc = calculator(2) # returns sub function
print(my_calc(5, 4)) # outputs 1</code>Nested (inner) functions allow the creation of helper functions that are scoped within a parent function, useful for tasks such as computing Fibonacci numbers:
<code>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)</code>Anonymous functions can be created with the lambda keyword. A lambda expression can replace a regular function definition for simple one‑line operations:
<code>mult = lambda x, y: x * y
print(mult(1, 2)) # returns 2</code>Lambda functions are also useful with built‑in higher‑order utilities such as map , filter , and reduce :
<code># map example
def multiply_by_four(x):
return x * 4
scores = [3, 6, 8, 3, 5, 7]
modified_scores = list(map(multiply_by_four, scores))
# same with lambda
modified_scores = list(map(lambda x: 4 * x, scores))
# filter example
even_scores = list(filter(lambda x: x % 2 == 0, scores))
# reduce example
from functools import reduce
sum_scores = reduce(lambda x, y: x + y, scores)</code>The article concludes with references for further reading on functional programming in Python.
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.