List of Functions

Ben Bacarisse ben.usenet at bsb.me.uk
Sun Mar 27 20:19:14 EDT 2016


Richard Riehle <rriehle at itu.edu> writes:

> Several months ago, I posted a question regarding how to create a list
> of functions.
<snip>
> 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

Anywhere you see a pattern there is the opportunity to make a function
that captures the pattern.  You could choose to have a button-function
making function like this:

  def makeButton(n):
      return lambda number: print('button%d = %d' % (n, number))

It's shame that anonymous functions (for that's what's being returned
here -- a function with no name) were born of a subject that used
arbitrary Greek letters for things.  We seem stuck with the mysterious
but meaningless "lambda" for a very simple and useful idea.  So maybe
it's better to do it with a named local function instead:

  def makeButton(n):
      def button(number): print('button%d = %d' % (n, number))
      return button;

And now you can use code to make the list since the button number is now
data.

  buttonList = [makeButton(i) for i in range(1, 3)]

-- 
Ben.



More information about the Python-list mailing list