Python *args and **kwargs for Variable Arguments

This is a detailed tutorial on *args and **kwargs in python. Learn to pass a variable number of keyworded and non-keyword arguments to a Python Function.

*args

It is used to specify that a function can take a variable number of arguments that are non-keyworded. This way you can pass as many non-keyworded arguments as you want to pass to a particular function.

The syntax is to use any variable name and before it, you just have to put the * symbol. In other words, it is not necessary to always write *args as a parameter inside the definition of the function rather you can also use any other valid variable name like *a, *ab, *arguments, *my_variables, etc. It’s just that parameter has to be followed by the asterisk symbol. This parameter will return a tuple that will contain all of the passed arguments to the function. The following example illustrates this.

def hello(*args):
    print(args)
    print(type(args))
    
hello(1,"Hey!",3,"Hello",True)

In the above code, we’ve defined a function named hello() and then we’ve passed the argument *args to let this function accept a variable number of parameters. Now we’re calling this function by passing five different parameters. Inside the function, we’ve just written two print statements, one to print the arguments tuple and another to show that the data type of this argument variable containing all of the parameters is a tuple.

Python *args Syntax

Variable Non-Keyworded Arguments

Example. The concept of accepting multiple and a variable number of arguments can help in defining a lot of useful functions. One such example is given below. We’ve defined a function named multiply that simply multiply any number of arguments provided during the function call.

def multiply(*numbers):
    result = 1
    for x in numbers:
        result *= x
    return result
    
result1 = multiply(1,2,3,4,5)
print(result1)
result2 = multiply(10,10,5.2)
print(result2)

We’re storing all of the passed arguments into a variable named numbers and as we know it is a tuple and a tuple is iterable. So, now we can use Python For Loop to iterate over it so as to multiply each and every argument and hence return the result.

*args Multiple Non Keyworded Arguments Example

Fixed & Variable Arguments Together

Example. You can also add some fixed arguments to a function first and then can add the variable argument keyword. The following example illustrates the same.

def addMul(toDo,*numbers):
    if toDo == "multiply":
        result = 1
        for x in numbers:
            result *= x
        return result
    elif toDo == "addition":
        result = 0
        for x in numbers:
            result += x
        return result
    else:
        return "ERROR"
    
result1 = addMul("multiply",1,2,3,4,5)
print(result1)
result2 = addMul("addition",10,10,5.2)
print(result2)

In the above python program, we’ve defined a function addMul(), that can either multiply or sum up the provided variable number of numerical arguments. But here the first argument is fixed and has to be a string-type argument stating whether to do Multiplication or addition of the provided arguments. We’ve used the If-elif Statement to do the conditional processing here.

Python Fixed & Variable Arguments Example Using *args

**kwargs

This also helps to define a function that has to accept multiple arguments but the only difference is that here you can accept multiple keyworded arguments while in *args, you could only accept non-keyworded arguments. There’s only a minor difference in the syntax as well. For the non-keyworded variable arguments, you’ve to put a single * symbol in front of the variable name, and here you have to put two * symbols consecutively before the start of the variable. For example, **kwargs, **numbers, **a, **abc, etc.

*args stores all of the arguments as a tuple while **kwargs as include the key-value type data, so it is stored as a Python Dictionary data type. The following example illustrates the arguments data is being stored and the data type of the variable is a dictionary.

def amazing(**kwargs):
    print(kwargs)
    print(type(kwargs))
    
amazing(name = "Gurmeet", age = "21")

We’ve defined a function named amazing() and inside it, we’ve written a variable **kwargs to accept multiple and variable-keyworded arguments. Then inside the body of the function, we simply used two print statements, one to print the dictionary containing the keyworded arguments that are being passed to the current function, and another statement simply prints that the data type of the variable kwargs is a dictionary.

Python **kwargs Syntax

Like *args, **kwargs is also very useful.

Variable Keyworded Arguments

def combineNameAge(**words):
    string = "Your name is " + words['name'] + " and your age is " + str(words['age']) + "."
    print(string)
    if(len(words)>2):
        print("Additional Arguments: ")
        for key, value in words.items():
            if(key == "name" or key == "age"):
                continue
            print(key + " : " + value)
    
combineNameAge(name = "Gurmeet Singh", age = 21)
combineNameAge(name = "Amandeep Singh", age = 12, standard = "7th", city = "Ludhiana")

In the above code, we’ve defined a function named combineNameAge() and it accepts a variable number of keyworded arguments. We’re simply combining the arguments with keys name and age into a single line of string and simply printing it out and if there are any additional arguments with any key, they’re simply printed as Additional Arguments. We’ve used the conditional statement to avoid the duplicate printing of the name and age arguments by continuing the loop in such a case using the continue statement.

Python Multiple Keyworded Arguments Example Using **kwargs

Using *args and **kwargs for calling a Function

You can also use *args and **kwargs syntax for calling functions with a variable number of arguments. The following arguments illustrate the same.

def example(par1, par2, par3):
    print("par1 is " + str(par1))
    print("par2 is " + str(par2))
    print("par3 is " + str(par3))

args = ("Hello!",1,True)
kwargs = {"par1": "Bye!", "par2": 2, "par3" : False}
example(*args)
example(**kwargs)

We’ve defined a function with three fixed parameters par1, par2 and par3. Now I’ve defined two variables args and kwargs and have assigned them the three parameters. For args, I create a tuple of three values and for kwargs I’ve defined a dictionary for the 3 key-value pair-type parameters. Then we’re simply calling the function by passing the *args and **kwargs syntax.

Python Calling Functions With *args And **kwargs Example

So, this clears the concept and you can use it in your own programs in a much more productive and useful way.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *