Understanding Functional Programming in Python: Concepts, Examples, and Techniques
This article explains functional programming concepts in Python, contrasting imperative and functional models, and demonstrates key techniques such as recursion, laziness, map, filter, reduce, lambda expressions, higher‑order functions, partial application, and comprehensions with clear code examples.
Functional programming focuses on describing *what* should be computed rather than *how* to compute it, emphasizing immutable data and side‑effect‑free functions.
In an imperative model, a program changes variable state step by step (e.g., assigning a = 5), whereas in a functional model the same computation is expressed as a pure function that returns a value without mutating external state.
Pure functional code avoids side effects; the following example shows a function that modifies a global variable, which is not allowed in a true functional style:
a = 3
def some_func():
global a
a = 5
some_func()
print(a)The output is 5, illustrating that the variable was changed, which functional programming forbids.
Functional functions are referentially transparent: given the same arguments they always produce the same result. This property enables memoization and other optimizations.
Recursion replaces loops in functional programming. The following Python recursive factorial demonstrates this:
def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n-1)Python’s functional features are lazy; expressions are evaluated only when needed. For example, the map function applies a transformation to each element of an iterable:
def square(num):
return num * num
x = [1, 2, 3, 4, 5]
print(list(map(square, x)))Using a lambda expression makes the same operation a one‑liner:
square = lambda x: x * x
print(square(3)) # 9The filter function selects items that satisfy a predicate. The example below keeps only negative numbers from a range:
x = range(-5, 5)
all_less_than_zero = list(filter(lambda num: num < 0, x))
print(all_less_than_zero)Higher‑order functions accept other functions as arguments or return them. The following shows a simple higher‑order function that applies a supplied function to a list of numbers:
def summation(nums):
return sum(nums)
def action(func, numbers):
return func(numbers)
print(action(summation, [1, 2, 3])) # 6Partial application (via functools.partial) fixes some arguments of a function, creating a new callable that requires fewer parameters:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(2)) # 4Comprehensions provide a concise way to build new collections. A list comprehension that squares each element is equivalent to using map: print([x * x for x in [1, 2, 3, 4]]) Comprehensions also support filtering with an if clause, replacing the need for separate filter calls:
x = range(-5, 5)
all_less_than_zero = [num for num in x if num < 0]
print(all_less_than_zero)Dictionary and set comprehensions work on any iterable, enabling compact construction of mappings and unique collections.
In summary, functional programming in Python offers elegant, pure constructs such as recursion, laziness, higher‑order functions, lambdas, partial application, and comprehensions, though some Python developers prefer more explicit, imperative styles.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
