Pass a variable number of positional arguments to a function.

In Keyword argument, we saw one way of passing a variable number of arguments (2 or 3) to a function. Here’s another way to pass a variable number of arguments to a function.

The asterisk in line 9 is new. See Arbitrary Argument Lists, and ‘If the form “*identifier” is present’ in Function definitions. See also ‘If the form “**identifier” is present’ in Function definitions, but we’re not going to do it this semester.

The asterisk in line 24 is old. It is the asterisk we saw in Pass list.

Line 12 is necessary because the only type of list that the join in line 13 will accept is a list of strings.

variablenumber.py

myPrint received 0 argument(s):
myPrint received 1 argument(s): 10
myPrint received 2 argument(s): 10 20
myPrint received 3 argument(s): Moe Larry Curly

myPrint received 1 argument(s): [10, 20, 30, 40]
myPrint received 4 argument(s): 10 20 30 40

Things to try

  1. Change lines 22–24 to
    myString = "abcd"
    myPrint(myString)   #1 argument, but that argument is a str
    myPrint(*myString)  #4 arguments
    
    myPrint received 1 argument(s): abcd
    myPrint received 4 argument(s): a b c d
    
  2. Change lines 22–24 to
    myRange = range(4)
    myPrint(myRange)   #1 argument, but that argument is a range
    myPrint(*myRange)  #4 arguments
    
    myPrint received 1 argument(s): range(0, 4)
    myPrint received 4 argument(s): 0 1 2 3