Functional Programming in Python - GeeksforGeeks

11 Oct, 2021
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.
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.
Python too supports Functional Programming paradigms without the support of any special features or libraries.
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 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 Listdef pure_func(List):          New_List = []          for i in List:        New_List.append(i**2)              return New_List      # Driver's codeOriginal_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]

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 listdef 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 codeL = [1, 2, 3, 4, 5]count = 0n = len(L)print(Sum(L, 0, n, count))
Output:
15

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 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:
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 + n     # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers)   # Does not Print the valueprint(results)  # For Printing valuefor result in results:    print(result, end = " ")Output:<map object at 0x7fae3004b630>
2 4 6 8 
Note: For more information, refer to Python map() function
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 + n     # We double all numbers using map() numbers = (1, 2, 3, 4) results = map(addition, numbers)   # Does not Print the valueprint(results)  # For Printing valuefor 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 the 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
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 the 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*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.
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*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 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 typesimmutable = "GeeksforGeeks"  # changing the values will# raise an errorimmutable[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

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.
Akanksha_Rai
pujasingg43
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()