def longlen(*strings): max = 0 for s in strings: if len(s) > max: max = len(s) return maxNotice that inside the function, strings is just an ordinary tuple; the asterisk before its name is only needed when the function is defined. If we call the function with a collection of strings as arguments, it will check them all, and return the maximum length of any of them:
>>> longlen('apple','banana','cantaloupe','cherry') 10
A similar technique can be used to create functions which can deal with an unlimited number of keyword/argument pairs. If an argument to a function is preceded by two asterisks, then inside the function, Python will collect all keyword/argument pairs which were not explicitly declared as arguments into a dictionary. When such an argument is used, it must be the last argument in the definition of the function. In this way, you can write a function to accept any named parameter, even if its name is not known when you are writing the function.
To illustrate, consider a trivial function which simply gathers all the keyword/value pairs which were not explicitly declared in the function definition into a dictionary called dict, and then prints the value of each declared argument. Two named arguments are provided before the final argument to show how Python deals with named arguments in the presence of an argument with two asterisks.
def printargs(a,b,**dict): print 'a=%s' % a print 'b=%s for k in dict.keys(): print '%s=%s' % (k,dict[k])We can test the function as follows:
>>> printargs(x='seven',a='six',b='five',next='four',last='three') a=six b=five next=four x=seven last=threeNotice that arguments a and b were not placed in the dictionary, since they were explicitly specified as part of the function definition.
In more complex situations, both kinds of special arguments (single and double asterisks) can be used in the same function. Once again, a trivial program will illustrate how this works:
def allargs(one,*args,**dict): print 'one=%s' % str(one) print 'Unnamed arguments:' for a in args: print '%s' % str(a) print 'Named arguments:' for k in dict.keys(): print '%s: %s' % (k,str(dict[k]))Since there is one named argument, allargs must be called with at least one argument, and the first argument will always be interpreted as the value of one. Here is the result when we call the function with more than one argument:
>>> allargs(12,'dog','cat',a=10,name='fred') one=12 Unnamed arguments: dog cat Named arguments: name: fred a: 10