What are the variable number of arguments in Python?

An argument is a variable, value, or object passed to a function or method as input. In Python, there are two ways to define a function that can take a variable number of arguments. Different forms of this type are:

  1. Positional arguments
  2. Keyword arguments

Positional arguments

Positional arguments are arguments that need to be included in the proper position or order. The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second, the third positional argument listed third, etc. General syntax for positional argument is: function(*iterable)

def positional_args(*argv):
for arg in argv:
print (arg)
positional_args ('Hello', 'Welcome', 'to', 'GITAM')

The arguments passed by the calling function are received by *argv. The passed arguments will be unpacked one by one within the function.

def positional_args (arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
positional_args ('Hello', 'Welcome', 'to', 'GITAM')

Keyword arguments

A keyword argument is an argument passed to a function or method that is preceded by a keyword and an equal sign. The general form is:

function(keyword = value)

Where function is the function name, the keyword is the keyword argument, and value is the value or object passed as that keyword.

In the code below, **kwargs is used to access the keyword arguments.

def key_args(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
key_args (first ='GITAM', mid ='for', last='GITAM')
def key_args (arg1, **kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
key_args ("Hi", first ='GITAM', mid ='for', last='GITAM')

*args vs. **kwargs

def var_arg(*args,**kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
var_arg ('GITAM','for','GITAM',first="GITAM",mid="for",last="GITAM")

Free Resources