[Tutor] Why use apply()?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun May 15 22:07:56 CEST 2005



On Thu, 12 May 2005, Bernard Lebel wrote:

> Just a generic question: why one would use apply()?
>
> In Learning Python, on page 357, there is an example of generating an
> instance using apply():
>
> class A:
>       def __init__( self, number ):
>              self.number = number
>
> a = apply( A, 3 )
>
> What is the benefit of doing this over simply creating an instance
> "the usual way":
>
> a = A( 3 )

Hi Bernard,


Just wanted to mention that Python allows us to define functions that take
a variable number of arguments:

######
>>> max(1, 2, 3, 4, 5)
5
>>> def mymax(*things):
...     biggest = things[0]
...     for x in things:
...         if x > biggest:
...             biggest = x
...     return biggest
...
>>> mymax("this", "is", "a", "test")
'this'
######


So this 'mymax' function can take in an arbitrary number of arguments.
This power comes with a slightly nonobvious problem: let's say that we had
a list of things:

######
>>> words = """hello world this is a test of the emergency broadcast
...         system""".split()
######

Can we call mymax() to get the maximum word in this list?



We might try to brute-force this:

     mymax(words[0], words[1], words[2], ...)

but there is a better approach:

    apply(mymax, words)

In newer versions of Python, we have syntactic sugar to make it easier to
say: "Apply this function with the elements of the input list":

    mymax(*words)


So apply (and the * stuff) really come into play when we're doing
functions with variable number of arguments.  Hope this helps!



More information about the Tutor mailing list