Functional Programming in Python
Last Updated :
02 Jan, 2025
Functional programming is a programming paradigm in which we try to bind everything in a 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 variables. 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 programming language also 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 needing them, and memorize the results since the results never change as long as the input doesn’t change.
Example:
Python
# 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]
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.
Example:
Let’s consider a program that will find the sum of all the elements of a list without using any for loop.
Python
# 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, etc.
Python
# 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 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
# 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 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
# 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
# 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
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
# 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. |
Similar Reads
__import__() function in Python
__import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
2 min read
Python min() Function
Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter. Example: Find Python min integer from the list [GFGTABS] Python numbers = [23,25,65,21,98] print(min(numbers)) [/GFGTABS]Output 21Python min() Function Syntaxmin(a, b, c, ..., key=fu
4 min read
Partial Functions in Python
Partial functions allow us to fix a certain number of arguments of a function and generate a new function. In this article, we will try to understand the concept of Partial Functions with different examples in Python. What are Partial functions and the use of partial functions in Python?Partial func
5 min read
Programming Paradigms in Python
Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach
4 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
4 min read
pow() Function - Python
pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example: [GFGTABS] Python print(pow(3,2)) [/GFGTABS]Output9 Explanation: pow(3, 2) calculates 32 = 9, where the
2 min read
Operator Functions in Python | Set 1
Python has predefined functions for many mathematical, logical, relational, bitwise etc operations under the module "operator". Some of the basic functions are covered in this article. 1. add(a, b) :- This function returns addition of the given arguments. Operation - a + b. 2. sub(a, b) :- This func
5 min read
Operator Functions in Python | Set 2
Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particul
5 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read
Nested Lambda Function in Python
Prerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then
2 min read