Skip to main content

Concepts of Functional Programming in Python with Examples

Functional Programming in Python

Functional programming it's not new jargon, it just is a style of writing programming and treating some values and some functions in a bit different way than we used to treat them in object-oriented programming.

What is Functional Programming?

Functional programming is a programming paradigm in which we evaluate the pure mathematical function as the principal method of computation. “What to solve” is more important in functional programming instead of “How to solve”. 

Concepts of Functional Programming

Now, every single programmer can debate in the world of functional programming whether this is functional or this is not but there are four core important things on which every single programmer is going to agree that yes these are part of functional programming.

Pure functions:

Pure Functions always produce the exact same output for the same argument irrespective of anything else. They have no side effects.

Recursion:

There is no “for” or “while” loop in functional languages. Recursion is the only way to achieve iteration.

Functions are First-Class Citizens:

In functional programming, we treat functions as first-class variables. These first-class variables can be passed as a parameter to a function or stored in data structures.

Variables are Immutable:

In functional programming, it is not possible to modify a variable after it’s been initialized. Instead of that, we can create new variables.


Functional Programming in Python

To support functional programming for any programming language, the functions of that programming language must have these properties.

  1. To take another function as an argument
  2. To return another function to its caller

Python is eligible in both these respects.

In python functions are first-class citizens, they have the same characteristics as values like strings and numbers. You would expect to do any operations with a string or a number you can do with functions as well.

Now below are some properties of python which are also the defining features of functional programming.

Ex. 1: You can assign a function to a variable. You can then use that variable the same as you would use the function itself. [First Class Function]



1 def func(): 2 print("I am function func()!") 3 func() 4 another_name = func 5 another_name()

OUTPUT:
I am function func()!


As you can see here, The assignment another_name = func on line 4 creates a new reference to func() named another_name. You can then call the function by either name, func, or another_name, as shown on lines 3 and 5.


Ex. 2: Functions in the python program does not change input values and return a new value. [Pure Functions]

def pure_func(List):
      
    New_List = []
      
    for i in List:
        New_List.append(i**2)
          
    return New_List
      

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]

A pure function that does not changes the input list and returns the new List.

Ex. 3: There are no “for” or “while” loops in functional languages. Recursion is the only way to achieve iteration. [Recursion]


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
      

L = [1, 2, 3, 4, 5]
count = 0
n = len(L)
print(Sum(L, 0, n, count))

OUTPUT:
15


Ex. 4: Immutability can be used for debugging in functional programming as it throws an error if any variable is being changed. Python also supports some immutable data types like string, tuple, numeric, etc. [Immutability]

# String data types
immutable = "Programmer-Bose"
  
# 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


Built-in Higher-order functions:

For processing iterable objects like lists and iterator easily, python has some built-in functions like:

  • 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

  • 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

  • Lambda functions

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]

The above-mentioned functions are also part of functional programming in the case of Python Programming Language.

Functional languages are great if you have a fixed set of things, and as your code updates, you add new operations which can be achieved by adding new functions which process with existing data types, and the existing functions are untouched.

Share your thoughts in the comment section.
Thank You.

Comments

Popular posts from this blog

Ordered Vs Unordered Data Structures in Python

Python has multiple data structures like Lists, Tuples, Dictionaries, Sets, and more . Some of them are Ordered and some are Unordered. This article will discuss  Ordered Vs Unordered Data Structures in Python. Lists It is a collection of a mutable ordered sequence of elements and can be accessed through indexing and defined inside []. Each element inside a List is called an item. From the above example, it is clear that the list maintains a sequence in which elements are inserted. So, it is an ordered data structure in python. Tuples It is a collection of immutable ordered elements, which follows a sequence in which elements are inserted. It is defined inside () and accessed through indexing. The above example shows that Tuples are ordered data structure and follow the sequence of insertion. Dictionaries Collection of items, in which items are defined as key-value pair in {}. Dictionaries are ordered data structures in python. It can be accessed through a specific key. Each key is sep

Making a URL Shortener using Python [Source Code Included] | URL Shortener API

In this tutorial , we are going to build a URL Shortener using Python and rebrand.ly API. We are only going to build the backend part of the application. Before jumping into the tutorial, you must know the basics of URL Shortener and API(Application Programming Interface). [This Article is originally published here ] What is a URL Shortener? So, as this tutorial is all about URL Shortener, it is best if you know the basics about it. To put it simply it is a tool that takes a long URL as an input and turns it into a more appealing short URL. Example: Long URL:  https://circuitician.com/esp32-email-notifier/ Shortened URL:  https://rb.gy/b7iqj6 As you can see the shortened URL is more appealing than the long one and it is more readable. Moreover, this shortened URL can be tracked for like no. of clicks, last-click time, etc. Shortened URLs are widely used by online marketers, promoters, and online entrepreneurs to promote their web links on the internet. If you share shortened URLs inste