Python is very powerful. It is easy to learn. Applications can be developed very quickly using python because of the simplicity.

Everything in python is an object. This includes functions also. Are you aware of the following features of functions in python. I was not aware during my initial few years.

  • Functions can be the elements inside various data structures like lists, dictionaries etc.

Few examples

Function as argument to another function

A Sample program in python to explain the implementation of using function as an argument of another function is given below.


def prefix_hello(name):
"""
User Defined function to prefix hello to the name
:param name: name
:return: Returns the name after prefixing hello
"""
return "Hello " + str(name)
def exec_func(function, operant_list):
"""
This function passes the each value in the operant list to the function.
———-
function : function (built-in or user defined)
operant_list : list of operand
——-
output: The results will be stored in a list and will be the output of this main function
"""
output = []
for operant in operant_list:
output.append(function(operant))
return output
if __name__ == '__main__':
# Example with built-in function int
value_list = [10.001, 190.1, 21.1, 20, 22, 24.5]
print(exec_func(int, value_list))
# Example with user defined function prefix_hello
name_list = ["amal", "sabitha", "edward"]
print(exec_func(prefix_hello, name_list))

Functions as elements within data structures like list or dict()

A simple implementation of passing list of functions as argument to another function is shared below.


from math import exp
def exec_func(function_list, p):
"""
This function passes the value p to each element in the function_list.
Each element in function_list is a function
———-
function_list : a list of functions
p : operand
——-
output: The results will be stored in a list and will be the output of this main function
"""
output = []
for function in function_list:
output.append(function(p))
return output
if __name__ == '__main__':
sample_list = [str, abs,exp,int]
print(exec_func(sample_list, 10.0001))

I hope this will help someone. 🙂

 

Advertisement