Open In App

Functional Programming in Python

Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve“. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables.

Concepts of Functional Programming

Any Functional programming language is expected to follow these concepts.



Functional Programming in Python

Python too supports Functional Programming paradigms without the support of any special features or libraries.

Pure Functions

As Discussed above, pure functions have two properties.



The second property is also known as immutability. The only result of the Pure Function is the value it returns. They are deterministic. Programs done using functional programming are easy to debug because pure functions have no side effects or hidden I/O. Pure functions also make it easier to write parallel/concurrent applications. When the code is written in this style, a smart compiler can do many things – it can parallelize the instructions, wait to evaluate results when needing them, and memorize the results since the results never change as long as the input doesn’t change.

Example:




# Python program to demonstrate
# pure functions
  
  
# A pure function that does Not
# changes the input list and 
# returns the new List
def pure_func(List):
      
    New_List = []
      
    for i in List:
        New_List.append(i**2)
          
    return New_List
      
# Driver's code
Original_List = [1, 2, 3, 4]
Modified_List = pure_func(Original_List)
  
print("Original List:", Original_List)
print("Modified List:", Modified_List)

Output:

Original List: [1, 2, 3, 4]
Modified List: [1, 4, 9, 16]

Recursion

During functional programming, there is no concept of for loop or while loop, instead recursion is used. Recursion is a process in which a function calls itself directly or indirectly. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. A question may arise what is base case? The base case can be considered as a condition that tells the compiler or interpreter to exit from the function.

Note: For more information, refer Recursion

Example: Let’s consider a program that will find the sum of all the elements of a list without using any for loop.




# Python program to demonstrate
# recursion
  
  
# Recursive Function to find
# sum of a list
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

Functions are First-Class and can be Higher-Order

First-class objects are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects.

Properties of first class functions:




# Python program to demonstrate
# higher order functions
  
  
def shout(text): 
    return text.upper() 
    
def whisper(text): 
    return text.lower() 
    
def greet(func): 
    # storing the function in a variable 
    greeting = func("Hi, I am created by a function passed as an argument."
    print(greeting)  
    
greet(shout) 
greet(whisper) 

Output:

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, I am created by a function passed as an argument.

Note: For more information, refer to First Class functions in Python.

Built-in Higher-order functions

To make the processing of iterable objects like lists and iterator much easier, Python has implemented some commonly used Higher-Order Functions. These functions return an iterator that is space-efficient. Some of the built-in higher-order functions are:

Immutability

Immutability is a functional programming paradigm can be used for debugging as it will throw an error where the variable is being changed not where the value is changed. Python too supports some immutable data types like string, tuple, numeric, etc.

Example:




# Python program to demonstrate 
# immutable data types
    
  
# String data types
immutable = "GeeksforGeeks"
  
# changing the values will
# raise an error
immutable[1] = 'K'

Output:

Traceback (most recent call last):
  File "/home/ee8bf8d8f560b97c7ec0ef080a077879.py", line 10, in 
    immutable[1] = 'K'
TypeError: 'str' object does not support item assignment

Difference between Functional Programming and Object Oriented Programming

Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.

Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

FUNCTIONAL PROGRAMMING OBJECT ORIENTED PROGRAMMING
This programming paradigm emphasizes on the use of functions where each function performs a specific task. This programming paradigm is based on object oriented concept.Classes are used where instance of objects are created
Fundamental elements used are variables and functions.The data in the functions are immutable(cannot be changed after creation). Fundamental elements used are objects and methods and the data used here are mutable data.
It follows declarative programming model. It follows imperative programming model.
It uses recursion for iteration. It uses loops for iteration.
It is parallel programming supported. It does not support parallel programming.
The statements in this programming paradigm does not need to follow a particular order while execution. The statements in this programming paradigm need to follow a order i.e., bottom up approach while execution.

Article Tags :