Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Functional Programming in Python 
2.1.
Pure Functions 
2.2.
Immutability
2.3.
Higher-Order Functions
2.3.1.
Map()
2.3.2.
filter() 
2.4.
Recursion
2.5.
Lambda Expressions
3.
Difference between Functional Programming and Object-Oriented Programming
4.
Frequently Ask Questions
4.1.
Why is Python a functional programming language?
4.2.
In functional programming in Python, what is the concept of side effects?
4.3.
How can a competent compiler execute functional programming in Python code?
4.4.
What exactly is "modular design," and why does it matter?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Functional Programming in Python

Author Muskan Gupta
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Functional programming in Python is a significant programming paradigm that is strongly tied to the mathematical underpinnings of computer science. We define it as a language that transforms data using functions.

Python isn't functional programming in the Python language, although it does use some of its features in conjunction with other programming paradigms. Python makes it simple to write code in various styles, each of which may offer the optimal answer for the problem at hand.

Source

In this blog, we will learn about the concept of Functional Programming in Python

So, let's begin!

Also See, Intersection in Python, Swapcase in Python

Functional Programming in Python 

Declarative languages are functional languages. They tell the computer what they want as a result. On the other hand, imperative languages tell the computer what actions to take to solve a problem. Python is typically written in an imperative style. However, it can also be written in a declarative form if appropriate.

Purely functional programming in the Python language, Haskell influenced some of Python's features. Let's look at some elements that might be considered desirable functional traits to understand better what a functional language is.

Pure Functions 

If you'd like functions to be pure, do not change the input value or any data outside the function's scope.

This makes testing the function we build a lot easier. We know we'll get the same outcome every time we execute the function with the same input because it doesn't modify the state of any variables.

 

Example

def multiply_2_pure(numbers):
    new_numbers = []
    for n in numbers:
        new_numbers.append(n * 2)
    return new_numbers

original_numbers = [1, 3, 5, 10]
changed_numbers = multiply_2_pure(original_numbers)
print(original_numbers) # [1, 3, 5, 10]
print(changed_numbers) # [2, 6, 10, 20]

This example for a pure function to multiply numbers by 2

The original list of numbers is unchanged, and we don't reference any other variables outside of the function, so it is pure.

Immutability

Have you ever had a bug where you wondered how a variable you set to 25 became none? If the variable had been immutable, the error would have been thrown when modified, not when the changed value had already impacted the software; the bug's primary cause might have been found earlier.

Immutable data types are available in Python, with the Tuple being one of the most prominent. Consider the Tuple in comparison to a changeable List:

mutable_collection = ['Tim', 10, [4, 5]]
immutable_collection = ('Tim', 10, [4, 5])

 

The following are the basic forms of data that can be read:

print(mutable_collection[2]) # [4, 5]
print(immutable_collection[2]) # [4, 5]

 

Let's enhance the second value of mutable_collection from 10 to 15.

mutable_collection[1] = 15

 

With the tuple, this fails.

immutable_collection[1] = 15
TypeError: The issue you'll see is that the 'tuple' object doesn't permit item assignment.

 

A Tuple could appear to be a changeable object in an unusual case. For example, if we wish to alter the immutable collection's list from [4, 5] to [4, 5, 6], we can do it as follows:

immutable_collection[2].append(6)
print(immutable_collection[2]) # [4, 5, 6]

 

Because a list is a changeable object, this works. Let's change the list back to [4, 5].

immutable_collection[2] = [4, 5]
# This throws a standard error:
# TypeError: 'Item assignment is not supported by the 'tuple' object.

 

It fails just as we predicted. While the contents of a changeable object in a tuple can be changed, the reference to the mutable object in memory cannot be changed.

Higher-Order Functions

Python has implemented some commonly used Higher-Order Functions to make processing iterable objects like lists and iterators considerably easier. These functions produce a space-efficient iterator. The following are some of the built-in higher-order functions:

 

Map()

We can use the map function to apply a function to each element of an iterable object. If we had a list of names and wanted to add a greeting to the Strings, we could do something like this:

 

Example 

names = ['Muskan', 'Jason', 'Yusef', 'Rajesh']
greeted_names = map(lambda x: 'Hello ' + x, names)
# This prints something similar to: <map object at 0x10ed93cc0>
print(greeted_names)
# Recall, that map returns an iterator 
# In a for loop, we may print all of the names.
for name in greeted_names:
    print(name)

 

Output

<map object at 0x000001C368126F50>
Hello Muskan
Hello Jason
Hello Yusef
Hello Rajesh

 

filter() 

The filter() method filters a sequence using a function that checks if each element in the sequence is true or not.

 

Example 

def fun(variable):  
    letters = ['a', 'e', 'i', 'o', 'u'] 
    if (variable in letters): 
        return True
    else: 
        return False
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'] 
filtered = filter(fun, sequence) 
print('The filtered letters are:') 
for s in filtered: 
    print(s) 

 

Output

The filtered letters are:
e
e

 

This Python program demonstrates the working of the filter.

Recursion

There is no such thing as a for loop or a while loop in functional programming in Python. Recursion is employed instead. A procedure in which a function calls itself directly or indirectly is known as recursion. The recursive program provides the answer to the base case, and the solution to the larger problem is represented in terms of lesser concerns. A question may arise: what is the base case? The base case can be considered a condition that tells the compiler or interpreter to exit from the function.

 

Example

Consider a program that calculates the sum of all list elements without utilizing any loops.

def Sum(L, i, n, count):
# Base case
if n <= i:
        return count
    count += L[i]
    # Going into the recursion
    count = Sum(L, i + 1, n, count)
    return count
# Driver's code
L = [1, 2, 3, 4, 5]
count = 0
n = len(L)
print(Sum(L, 0, n, count))

 

Output

15

 

This Python program demonstrates recursion. It has a recursive function to find some of a list.

Lambda Expressions

An anonymous function is a lambda expression. In Python, we use the def keyword to define a function and give it a name. We can define a function much faster with lambda expressions.

 

Example

Let's make a Higher Order Function called hof product that returns a function that multiplies a number by a given value:

def hof_product(multiplier):
    return lambda x: x * multiplier
mult6 = hof_product(6)
print(mult6(6)) # 36

 

Output

36

 

The function arguments follow the keyword lambda in a lambda expression. The code provided by the lambda is placed after the colon; this ability to build functions "on the go" is quite useful when working with Higher-Order Functions.

You can practice by yourself with the help of online python compiler for better understanding.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Difference between Functional Programming and Object-Oriented Programming

Object-oriented Programming

Functional Programming

It focuses on how we are doing. It focuses on what we are doing.
It has a stateful programming model It has a stateless programming model
It supports abstraction over data only It supports abstraction over data and behavior
A state exists. A state doesn't exist.
An object is the primary manipulation unit. The function is the primary manipulation unit.

 

Recommended Topic, Python Round Function.

Since you got an overall idea of Functional Programming in Python, now we will close this article with faqs.

You can also know about Python Square Root here.

Frequently Ask Questions

Why is Python a functional programming language?

Python authorizes us to code in a functional, declarative style. It keeps many standard functional characteristics like lambda expressions and the map and filter functions. Yet, the Python community does not believe the use of functional Programming techniques is the best approach at all times.

In functional programming in Python, what is the concept of side effects?

Side effects are state changes that occur outside of a called function, which functional programming in Python tries to reduce as much as possible by separating them from the remaining software.

How can a competent compiler execute functional programming in Python code?

A good compiler would run by parallelizing FP-style instructions, waiting for the results to be assessed, and memorizing the result when needed.

What exactly is "modular design," and why does it matter?

Modular design entails using small, self-contained modules that may be coded fast, reused frequently, and independently tested. This improves productivity and efficiency in development.

Conclusion

In this article, we have extensively discussed Functional Programming in Python, immutability, and lambda expression. The article explains the Recursion and High-Order functions with examples.

Recommended Readings:

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Previous article
Python os.system
Next article
Python os path join
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass