Fundamentals 10 min read

Introduction to Functional Programming in Python

This article provides a beginner-friendly overview of functional programming concepts in Python, covering first‑class functions, callable objects, higher‑order functions, lambda expressions, and the use of map, filter, and reduce with illustrative code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Introduction to Functional Programming in Python

Functional programming has become increasingly popular, and modern languages like Python now support its techniques. This article introduces the basics of functional programming in Python.

First‑class functions : In Python, functions are first‑class citizens, meaning they can be assigned to variables, passed as arguments, stored in data structures, and returned from other functions.

<code>def foo():
    print("foo")
</code>
<code>bar = foo
bar()  # will print "foo" to the console
</code>

Because functions are objects, they can be stored in dictionaries or other collections:

<code># store in dictionary
mapping = {
    0: foo,
    1: bar
}
x = input()  # get integer value from user
mapping[x]()  # call the function returned by dictionary access
</code>

Callable objects : Any object implementing the __call__ method can be invoked like a function.

<code>class Greeter:
    def __init__(self, greeting):
        self.greeting = greeting
    def __call__(self, name):
        return self.greeting + " " + name

morning = Greeter("good morning")  # creates the callable object
print(morning("john"))  # prints "good morning john"

callable(morning)  # true
callable(145)      # false
</code>

Higher‑order functions : Functions that accept other functions as arguments or return them. Example of a simple iterator:

<code>def iterate(list_of_items):
    for item in list_of_items:
        print(item)
</code>

To make the operation customizable, a higher‑order version can be written:

<code>def iterate_custom(list_of_items, custom_func):
    for item in list_of_items:
        custom_func(item)
</code>

Functions can also be returned to select behavior at runtime:

<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
print(my_calc(5, 4))  # 1
</code>

Nested functions : Functions defined inside other functions can act as helpers and keep the outer scope clean.

<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>

Lambda expressions : Anonymous single‑line functions created with the lambda keyword.

<code>mult = lambda x, y: x * y
print(mult(1, 2))  # returns 2
</code>

Lambda functions can be used directly without naming:

<code>(lambda x, y: x * y)(9, 10)  # returns 90
</code>

They are also handy for initializing default values in data structures:

<code>import collections
pre_fill = collections.defaultdict(lambda: (0, 0))
</code>

Map, Filter, Reduce :

Map applies a function to each item of an iterable:

<code>def multiply_by_four(x):
    return x * 4
scores = [3, 6, 8, 3, 5, 7]
modified_scores = list(map(multiply_by_four, scores))
# modified_scores is now [12, 24, 32, 12, 20, 28]
</code>

Using a lambda simplifies the same operation:

<code>modified_scores = list(map(lambda x: 4 * x, scores))
</code>

Filter selects items that satisfy a predicate:

<code>even_scores = list(filter(lambda x: True if (x % 2 == 0) else False, scores))
# even_scores = [6, 8]
</code>

Reduce aggregates a sequence into a single value:

<code>from functools import reduce
sum_scores = reduce(lambda x, y: x + y, scores)  # sum_scores = 32
</code>

The article concludes that while it provides a fairly complete introduction to functional programming in Python, it does not delve deeply into advanced topics.

PythonlambdaFunctional ProgrammingmapreduceFilterHigher-order Functionsfirst-class functions
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.