Python Tutorial, Release 3.9.5 4.7.4 Arbitrary Argument Lists 4.7.5 Unpacking Argument Lists 4.7.6 Lambda Expressions Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of argu- ments. These arguments will be wrapped up in a tuple (see Tuples and Sequences ). Before the variable number of arguments, zero or more normal arguments may occur. Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remain- ing input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments. The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the$_{*}$ -operator to unpack the arguments out of a list or tuple: In the same fashion, dictionaries can deliver keyword arguments with the$_{**}$ -operator: Small anonymous functions can be created with the$_{lambda}$keyword. This function returns the sum of its two arguments: lambda a, b: a+b . Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope: (continues on next page) 4.7. More on Defining Functions 27 >>>def concat(*args, sep="/"): ... return sep.join(args) ... >>> concat( "earth","mars","venus") 'earth/mars/venus' >>> concat( "earth","mars","venus", sep=".") 'earth.mars.venus' >>> list(range(3,6)) # normal call with separate arguments [3, 4, 5] >>> args =[3,6] >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] >>>def parrot(voltage, state ='a stiff', action='voom'): ... print("-- This parrot wouldn 't", action, end ='') ... print("if you put", voltage, "volts through it. ", end='') ... print("E's", state,"!") ... >>> d ={ "voltage ":"four million","state":"bleedin'demised","action":"VOOM "} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin ↪ → ' demised ! >>>def make_incrementor(n): ... return lambda x: x+n ... >>> f =make_incrementor( 42 ) >>> f(0) def write_multiple_items (file, separator, *args): file.write(separator.join(args))