Fundamentals 10 min read

Unlock Python’s First-Class Functions: From Basics to Advanced Functional Tricks

This article explains how Python treats functions as first‑class objects, showing how to assign them to variables, pass them as arguments, return them from other functions, store them in data structures, and use functional tools like lambda, map, filter, and reduce to write more reusable and expressive code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Unlock Python’s First-Class Functions: From Basics to Advanced Functional Tricks

First-Class Functions

In Python, functions are first‑class citizens, meaning they have the same status as other data types such as int.

Therefore we can assign a function to a variable, pass it as an argument to other functions, store it in data structures like dicts, and return it from other functions.

Treating Functions as Objects

Since other data types (string, list, int) are objects, functions are also objects. Example function foo prints its name:

def foo():
    print("foo")

We can assign foo to another variable and call it:

bar = foo
bar()  # will print "foo" to the console

Callable Objects

An object that implements the __call__ method is callable, behaving like a function. Example:

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

Creating a callable instance:

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

We can test callability with the built‑in callable function:

callable(morning)  # true
callable(145)      # false

Functions in Data Structures

Functions can be stored in containers just like any other object. Example dictionary mapping integers to functions:

mapping = {
    0: foo,
    1: bar
}
x = input()  # get integer value from user
mapping[int(x)]()  # call the selected function

Higher‑Order Functions

Functions that accept other functions as arguments or return functions are called higher‑order functions, a key concept in functional programming.

Example of a simple iterator:

def iterate(list_of_items):
    for item in list_of_items:
        print(item)

To make the action customizable, we define a higher‑order version:

def iterate_custom(list_of_items, custom_func):
    for item in list_of_items:
        custom_func(item)

Nested Functions

Functions can be defined inside other functions, useful for creating helper sub‑functions that support the outer function.

Lambda Expressions

Anonymous single‑line functions can be created with the lambda keyword. Example:

mult = lambda x, y: x * y
mult(1, 2)  # returns 2

Lambda functions are implicitly returned and can be used directly:

(lambda x, y: x * y)(9, 10)  # returns 90

Map, Filter, Reduce

The map function applies a given function to each item of an iterable, returning a new iterable.

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

The filter function selects items that satisfy a predicate:

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

The reduce function aggregates a sequence into a single value:

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

This article provides an introductory overview of functional programming in Python.

Best Practices for Using Functional Programming in Python: https://kite.com/blog/python/functional-programming/

Functional Programming Tutorials and Notes: https://www.hackerearth.com/zh/practice/python/functional-programming/functional-programming-1/tutorial/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.