13.3. Variable number of parameters

A function can take additional optional arguments by prefixing the last parameter with an * (asterix). Optional arguments are then available in the tuple referenced by this parameter.

>>> def f(*p):
...   print p
>>> f()
()
>>> f('a')
('a',)
>>> f('a', 'b')
('a', 'b')
>>> f('a', 'b', 'c')
('a', 'b', 'c')
	
To illustrate how you could use this feature, look at the following function, which generates all possible digests with 2 enzymes:
def all_2_digests(enzymes):
    digests = []
    for i in range(len(enzymes)):
        for k in range(i+1, len(enzymes)):
            digests.append( [enzymes[i], enzymes[k]] )
    return digests

>>> all_2_digests(['EcoRI', 'HindIII', 'BamHI'])
[['EcoRI', 'HindIII'], ['EcoRI', 'BamHI'], ['HindIII', 'BamHI']]
	
This function takes a list. We can transform this function such that it can be applied as follow:
>>> all_2_digests('EcoRI', 'HindIII', 'BamHI')
[['EcoRI', 'HindIII'], ['EcoRI', 'BamHI'], ['HindIII', 'BamHI']]
	
instead of:
>>> all_2_digests(['EcoRI', 'HindIII', 'BamHI'])
[['EcoRI', 'HindIII'], ['EcoRI', 'BamHI'], ['HindIII', 'BamHI']]
	
To achieve this, the enzymes parameter is defined as follows:
def all_2_digests(*enzymes):
    digests = []
    for i in range(len(enzymes)):
        for k in range(i+1, len(enzymes)):
            digests.append( [enzymes[i], enzymes[k]] )
    return digests
	

Optional variables can also by passed as keywords, if the last parameter is preceded by **. In this case, the optional variables are available within the function as a dictionary.

def hello(name, **profile):
   print "Hello", name
   if profile.has_key('origin'):
       print "We hope you had a nice flight from", profile['origin']
   if profile.has_key('duration'):
       print "Enjoy your %d days vacation!! " % profile['duration']

	
To call this function, just pass arguments by name:
>>> hello("kate")
Hello kate
>>> hello("kate", duration=10)
Hello kate
Enjoy your 10 days vacation!! 
>>> hello("kate", duration=10, origin="France")
Hello kate
We hope you had a nice flight from France
Enjoy your 10 days vacation!!