List of Functions

Richard Riehle rriehle at itu.edu
Sun Mar 27 15:38:16 EDT 2016


Several months ago, I posted a question regarding how to create a list of functions.  I quickly solved the problem on my own, but I am just now getting around to sharing my solution.  It was actually quite simple, and also quite useful for the problem I had at hand.  Below is an example of one way to do this.  There are actually some other solutions.

This solution is based on the fact that Python functions are first-class objects, and therefore enable one to emulate functional programming.   

Consider that we might need a list of buttons, each of which can behave differently based on a parameter list.   First, we define three button functions with a parameter.  Then, we create a list of those functions. 

The tricky part is how we formulate the actual function call.   I demonstrate this in the last two lines of the code below.   

I realize that this seems trivial to many experience Pythonistas.  But it might prove useful for those who are relative newcomers to the language.  In any case, I hope someone can find it helpful.  

>>> def button1(number):
	print ('button1 = ', number)  ## define the buttons
>>> def button2(number):
	print ('button2 = ', number)
>>> def button3(number):
	print ('button3 = ', number)	
>>> buttonList = [button1, button2, button3]  ## create the list
>>>
>>> buttonList [1] (25)          ## using positional association
button2 =  25                    
>>>buttonList [0] (number = 78)  ## using named association
button1 = 78



More information about the Python-list mailing list