Skip to content
Related Articles

Related Articles

Improve Article
Functional Programming in Python
  • Difficulty Level : Expert
  • Last Updated : 16 Jul, 2020

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.

  • Pure Functions: These functions have two main properties. First, they always produce the same output for the same arguments irrespective of anything else. Secondly, they have no side-effects i.e. they do modify any argument or global variables or output something.
  • Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional languages is implemented through recursion.
  • Functions are First-Class and can be Higher-Order: First-class functions are treated as first-class variable. The first-class variables can be passed to functions as a parameter, can be returned from functions or stored in data structures.
  • Variables are Immutable: In functional programming, we can’t modify a variable after it’s been initialized. We can create new variables – but we can’t modify existing variables.

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.

  • It always produces the same output for the same arguments. For example, 3+7 will always be 10 no matter what.
  • It does not change or modifies the input variable.

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 need 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 exits 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:



  • A function is an instance of the Object type.
  • You can store the function in a variable.
  • You can pass the function as a parameter to another function.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …




# 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 iterable objects like lists and iterator much easier, Python has implemented some commonly used Higher-Order Functions. These functions return an iterator which is space-efficient. Some of the built-in higher-order functions are:

  • Map(): map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)

    Syntax: map(fun, iter)

    Parameters:
    fun: It is a function to which map passes each element of given iterable.
    iter: It is a iterable which is to be mapped.

    Return Type: Returns an iterator of map class.

    Example:




    # Python program to demonstrate working 
    # of map. 
        
    # Return double of n 
    def addition(n): 
        return n +
        
    # We double all numbers using map() 
    numbers = (1, 2, 3, 4
    results = map(addition, numbers) 
      
    # Does not Prints the value
    print(results)
      
    # For Printing value
    for result in results:
        print(result, end = " ")

    Output:

    <map object at 0x7fae3004b630>
    2 4 6 8 
    

    Note: For more information, refer to Python map() function



  • filter(): The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

    Syntax: filter(function, sequence)

    Parameters:
    function: a function that tests if each element of a sequence true or not.
    sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.

    Return Type: returns an iterator that is already filtered.

    Example:




    # Python program to demonstrate working 
    # of filter. 
        
    # function that filters vowels 
    def fun(variable): 
          
        letters = ['a', 'e', 'i', 'o', 'u'
          
        if (variable in letters): 
            return True
        else
            return False
        
        
    # sequence 
    sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r'
        
    # using filter function 
    filtered = filter(fun, sequence) 
        
    print('The filtered letters are:'
      
    for s in filtered: 
        print(s) 

    Output:

    The filtered letters are:
    e
    e
    

    Note: For more information, refer to filter() in Python

  • Lambda functions: In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

    Syntax:

    lambda arguments: expression
    

    1) This function can have any number of arguments but only one expression, which is evaluated and returned.
    2) One is free to use lambda functions wherever function objects are required.
    3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
    4) It has various uses in particular fields of programming besides other types of expressions in functions.

    Example:




    # Python code to demonstrate
    # lambda
      
        
    cube = lambda x: x * x*
    print(cube(7)) 
        
        
    L = [1, 3, 2, 4, 5, 6]
    is_even = [x for x in L if x % 2 == 0]
      
    print(is_even)  

    Output:

    343
    [2, 4, 6]
    

    Note: For more information, refer to Python lambda.

Immutability

Immutability in 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 PROGRAMMINGOBJECT 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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :