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.
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.
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 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.
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, …
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)
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.
# Python program to demonstrate working
# of map.
# Return double of n
# We double all numbers using map()
# Does not Prints the value
# For Printing value
<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)
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.
# Python program to demonstrate working
# of filter.
# function that filters vowels
# using filter function
'The filtered letters are:'
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.
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.
# Python code to demonstrate
343 [2, 4, 6]
Note: For more information, refer to Python lambda.
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.
Traceback (most recent call last): File "/home/ee8bf8d8f560b97c7ec0ef080a077879.py", line 10, in
immutable = '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.|
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.
- Object Oriented Programming in Python | Set 1 (Class, Object and Members)
- Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
- Command Line Interface Programming in Python
- Python Input Methods for Competitive Programming
- CGI Programming in Python
- Socket Programming with Multi-threading in Python
- Python - Fastest Growing Programming Language
- Why is Python the Best-Suited Programming Language for Machine Learning?
- Difference Between Go and Python Programming Language
- Python | Linear Programming in Pulp
- Python program to find GSoC organisations that use a Particular Programming Language
- Programming Paradigms in Python
- Python | Implementing Dynamic programming using Dictionary
- Which Python Modules are useful for competitive programming?
- Comparison of Python with Other Programming Languages
- Mathematics Tricks For Competitive Programming In Python 3
- How to Create a Programming Language using Python?
- Python vs Other Programming Languages
- Incremental Programming in Python
- How to Setup VSCode with C, C++ and Python for Competitive Programming
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Akanksha_Rai