Concept of Functional Programming in Python

In this article series, we are going to discuss the Functional Programming Paradigm. We will also focus on the implementation of functional programming in Python.

Now, what do we mean by a Programming Paradigm?

By Programming Paradigm, we mean the approach or the way we think about solving a problem.

The reason Python is so popular is that it supports multiple programming paradigms. This includes 3 of the most popular paradigms i.e. Structural, Object-Oriented and Functional.

Also read: Use of decorators in Python

Let’s look more closely into the concept of functional programming.

Functional Programming

In functional programming, we treat functions as Objects.  Therefore, we can do the following things with functions:

  1. We can assign an identifier with a function.
  2. We Can pass functions as arguments to other functions.
  3. And we can return functions from another functions.

In technical terms, we call any entity, which satisfies the above requirements in a programming language as First Class Objects. Therefore, functions are treated as First Class Objects in functional programming.

Functional Programming in Python

In Python Function Programming often helps us in minimizing the code size to a large extent. Let’s take a situation where we have to square each number from a list of numbers and then filter out the numbers which are even from the resultant list.

# Function to square numbers in a list.
def sqr(nums):
    res = []
    for i in nums:
        res.append(i*i)

    return res

# Function to filter evens from a list.
def filt_even(nums):
    res = []
    for i in nums:
        if (i%2 == 0):
            res.append(i)
    
    return res

numlist = [1,2,3,4,5,6,7]
reslist = filt_even(sqr(numlist))

print(reslist)

The output of the above code is shown below:

Functional Programming in Python

The above-given operations can be reduced to a single line of code using Python as follows:

numlist = [1,2,3,4,5,6,7]
reslist =  list(filter(lambda x: x%2==0,list(map(lambda x : x*x,numlist))))
print(reslist)

# The 2nd line above can be broken down as follows:

# ilist = list(map((lambda x:x*x),numlist))
# Performs the operation of sqr() function in 
# above example

# reslist = list(filter(lambda x:x%2==0,ilist))
# Performs the operation of filt_even() function 
# in the above example.

In the above examples, we need to typecast the outputs of map() and filter() because, by default, both of them return map and filter type objects respectively.

Leave a Reply

Your email address will not be published. Required fields are marked *