Functional Programming in Python
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. It has the following syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming besides other types of expressions in functions. Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:
# Python code to illustrate cube of a number # showing difference between def() and lambda(). def cube(y): return y*y*y; g = lambda x: x*x*x print(g(7)) print(cube(5))
- Without using Lambda : Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
- Using Lambda : Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
filter(function, sequence) Parameters: function: 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. Returns: returns an iterator that is already filtered.
# 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)
The filtered letters are: e e
# a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13] # result contains odd numbers of the list result = filter(lambda x: x % 2 != 0, seq) print(list(result)) # result contains even numbers of the list result = filter(lambda x: x % 2 == 0, seq) print(list(result))
[1, 3, 5, 13] [0, 2, 8]
fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)
# 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) result = map(addition, numbers) print(list(result))
[2, 4, 6, 8]
# Double all numbers using map and lambda numbers = (1, 2, 3, 4) result = map(lambda x: x + x, numbers) print(list(result))
[2, 4, 6, 8]
The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module.
- At first step, first two elements of sequence are picked and the result is obtained.
- Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
- This process continues till no more elements are left in the container.
- The final returned result is returned and printed on console.
# python code to demonstrate working of reduce() # importing functools for reduce() import functools # initializing list lis = [ 1 , 3, 5, 6, 2, ] # using reduce to compute sum of list print ("The sum of the list elements is : ",end="") print (functools.reduce(lambda a,b : a+b,lis)) # using reduce to compute maximum element from list print ("The maximum element of the list is : ",end="") print (functools.reduce(lambda a,b : a if a > b else b,lis))
The sum of the list elements is : 17 The maximum element of the list is : 6