Functional Programming in Python: A Deep Dive
Daniel Hayes
Full-Stack Engineer · Leapcell
Overview of Functional Programming
Functional programming refers to a style where every part of the code is immutable and consists of pure functions. A pure function is one that is independent of others and, given the same input, always produces the same output.
In addition, functional programming has the characteristic of allowing a function to be passed as an argument to another function and also to return a function.
Examples of Pure Functions
For example, to double the values of elements in a list, the following function can be used:
def multiply_2(list): for index in range(0, len(list)): list[index] *= 2 return list
It should be noted that this code is not in the form of a pure function because the values of the elements in the list are modified. If the multiply_2()
function is called multiple times, the results will be different each time.
To make multiply_2()
a pure function, a new list needs to be created and returned, like this:
def multiply_2_pure(list): new_list = [] for item in list: new_list.append(item * 2) return new_list
Advantages and Disadvantages of Functional Programming
The advantages of functional programming mainly lie in the fact that the pure function and immutable characteristics make the program more robust and easier to debug and test. The disadvantages are mainly that there are many restrictions and it is difficult to write.
Note that in pure functional programming languages (such as Scala), there are no variables in the functions written, so it can be guaranteed that as long as the input is determined, the output is determined. In programming languages that allow the use of variables, due to the uncertain state of variables inside the function, the same input may result in different outputs.
Python allows the use of variables, so it is not a pure functional programming language. Python only provides partial support for functional programming, mainly including the three functions map()
, filter()
, and reduce()
, which are usually used together with lambda
anonymous functions. Next, the usage of these three functions will be introduced one by one.
Python's Functional Programming Support Functions
Python map() Function
The basic syntax of the map()
function is as follows:
map(function, iterable)
Here, the function
parameter represents a function to be passed in, which can be a built - in function, a custom function, or a lambda
anonymous function. The iterable
represents one or more iterable objects, such as lists, strings, etc.
The function of the map()
function is to call the specified function for each element in the iterable object and return a map
object.
Note that the function returns a map
object, which cannot be output directly. It can be displayed through a for
loop or the list()
function.
[Example 1] Multiply each element in the list by 2
listDemo = [1, 2, 3, 4, 5] new_list = map(lambda x: x * 2, listDemo) print(list(new_list))
The running result is:
[2, 4, 6, 8, 10]
[Example 2] Pass multiple iterable objects as parameters to the map() function
listDemo1 = [1, 2, 3, 4, 5] listDemo2 = [3, 4, 5, 6, 7] new_list = map(lambda x,y: x + y, listDemo1,listDemo2) print(list(new_list))
The running result is:
[4, 6, 8, 10, 12]
Note that since the map()
function is directly written in C language, it does not need to be called indirectly through the Python interpreter during runtime, and many optimizations have been made internally. Therefore, compared with other methods, this method has the highest running efficiency.
Python filter() Function
The basic syntax of the filter()
function is as follows:
filter(function, iterable)
In this format, the funcition
parameter represents a function to be passed in, and the iterable
represents an iterable object.
The function of the filter()
function is to use the function
function to judge each element in iterable
and return True
or False
. Finally, the elements that return True
are combined into a new traversable collection.
[Example 3] Return all even numbers in a list
listDemo = [1, 2, 3, 4, 5] new_list = filter(lambda x: x % 2 == 0, listDemo) print(list(new_list))
The running result is:
[2, 4]
[Example 4] The filter() function accepts multiple iterable objects
listDemo = [1, 2, 3, 4, 5] new_list = map(lambda x,y: x-y>0,[3,5,6],[1,5,8] ) print(list(new_list))
The running result is:
[True, False, False]
Python reduce() Function
The reduce()
function is usually used to perform some cumulative operations on a collection. Its basic syntax is:
reduce(function, iterable)
Here, the function
must be a function with two parameters, and the iterable
represents an iterable object.
Note that since the reduce()
function has been removed in Python 3.x and placed in the functools
module, the functools
module needs to be imported before using this function.
[Example 5] Calculate the product of elements in a list
import functools listDemo = [1, 2, 3, 4, 5] product = functools.reduce(lambda x, y: x * y, listDemo) print(product)
The running result is:
120
Summary
Generally, when performing some operations on elements in a collection, if the operations are very simple, such as addition, accumulation, etc., map()
, filter()
, and reduce()
should be considered first. In addition, when the data volume is very large (such as in machine learning applications), functional programming representation is usually preferred because of its higher efficiency.
Of course, when the data volume is not large, methods such as for
loops can also be used. However, if some more complex operations need to be performed on the elements in the collection, considering the readability of the code, for
loops are usually used.
Leapcell: The Next - Gen Serverless Platform for Web Hosting, Async Tasks, and Redis
Finally, I recommend the best platform for deploying Python apps: Leapcell
1. Multi - Language Support
- Develop with JavaScript, Python, Go, or Rust.
2. Deploy unlimited projects for free
- Pay only for usage — no requests, no charges.
3. Unbeatable Cost Efficiency
- Pay - as - you - go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
4. Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real - time metrics and logging for actionable insights.
5. Effortless Scalability and High Performance
- Auto - scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the documentation!
Leapcell Twitter: https://x.com/LeapcellHQ