Learn python *args and **kwargs with simple examples


Written By - Bashir Alam
Advertisement

Related Searches: python kwargs, python args, kwargs, python keyword arguments, python args kwargs, what is an argument in python, python kwargs example, python pass arguments, args and kwargs in python, function arguments python, keyword arguments, python varargs, kwargs get, variable number of arguments python, what are args, python argument list, python variable arguments, what is kwargs in python, python args example, argument to function python, python variable arguments example, star keyword, python args kwargs tutorial, pass args in python

 

Introduction to Python **kwargs

When we create a function in python, we specify the number of arguments that the function can take. If we provide fewer or more arguments than the specified one, the python interpreter will give an error. However, in python we can pass a number of arguments to a function using special symbols.

The two special symbols are *args and **kwargs.

In this section, we will learn about python kwargs and see how we can pass a number of arguments to a function without getting any error using the python kwargs method. Moreover, we will take different examples and various scenarios to use python kwargs. All in all, this tutorial covers all the concepts that you need to know in order to get started working with python kwargs.

 

Getting started with Python **kwargs

A python kwargs is a dictionary of keyword arguments. we put two ** before kwargs which allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.

An example of of a keyword arguments can be:

school(name=UCA, classes=30)

In this section, we will cover the syntax and take some examples of python **kwargs.

 

Syntax of Python kwargs

The special syntax of python kwargs in function definitions is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

Advertisement

The simple syntax of python kwargs look like this:

def function_name(**kwargs):
<function statements>

The python kwargs takes keywords argument, which is where we provide a name to the variable as we pass it into the function. We can take it as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over **kwargs there doesn’t seem to be any order in which they were printed out.

The type of python kwargs is python dictionary.

# Python kwargs function
def main(**kwargs):

   # print type of kwargs
   print("The type of Python kwargs: ")
   print(type(kwargs))

Output:

The type of Python kwargs:
<class 'dict'>

See that the type of argument is a dictionary. If we will provide any other data typed argument, Python will return an error. See the example below:

# Python kwargs function
def main(**kwargs):

   # print type of kwargs
   print("The type of Python kwargs: ")
   print(type(kwargs))

# calling function  
main(1, 2, 4,5)

Output:

        main(1, 2, 4,5)
TypeError: main() takes 0 positional arguments but 4 were given

Now let us provide key-value pairs as an argument and see if we get an error or not! See the example below:

# Python kwargs function
def main(**kwargs):

   # printing python kwargs
   print("The elements of Python kwargs: ")
   print((kwargs))

# calling function  
main(a=1, b=2, c=4,d=5)

Output:

Advertisement
The elements of Python kwargs:
{'a': 1, 'b': 2, 'c': 4, 'd': 5}

 

Examples using Python kwargs

Now let us see how we can use **kwargs to take multiple arguments and print out all the sum of all the arguments, but first, let see a python function that takes multiple arguments and return the sum of arguments. See the example below:

# python function with multiple arguments
def main(num1, num2, num3):
   print("The sum of arguments is")
   # printing the sum
   print(num1 + num2 + num3)

# calling function
main(2, 3, 4)

Output:

The sum of arguments is
9

Now let us say we have more arguments than the specified one in the main function. Let us pass 5 arguments and See what happens. See the example below:

# python function with multiple arguments
def main(num1, num2, num3):

   print("the sum of arguments is:")
   # printing the sum
   print(num1 + num2 + num3)

# calling function
main(2, 3, 4, 5, 6)

Output:

      main(2, 3, 4, 5, 6)
TypeError: main() takes 3 positional arguments but 5 were given

Notice that we get an error because we passed more arguments.

Now here comes python **kwargs to solve such problems. With **kwargs we don't need to specify the number of arguments, but we can pass as many as we want while calling the function.

Advertisement

See the example below:

# python function with multiple arguments
def main(**kwargs):

   # variables
   sum = 0
   print("the sum of arguments is:")

   # iterating over dictionary of arguments
   for keys, value in kwargs.items():
       sum+=value

   # returns sum of arguments
   return sum

# calling function
print(main(one=2, two=3,three= 4,four= 5, five=6))

Output:

the sum of arguments is:
20

Notice that we had just passed **kwargs in our function, which means now our function can any number of of keywords arguments.

Using the python kwargs method we can also print the keys of the arguments as well. See the example which prints key-values of argument.

# main function
def main(**kwargs):
   print("the key-values are:")

   # iterating over dictionary of arguments
   for key, value in kwargs.items():

       # printing key and ValuesView
       print(key, value)

# calling function
main(one=2, two=3,three= 4,four= 5, five=6)

Output:

the key-values are:
one 2
two 3
three 4
four 5
five 6

One of the good thing about python **kwargs is that they allow us to pass any data type as an argument. See the example below which provides strings values.

# main function
def main(**kwargs):

   print("the key-values are:")
   # iterating over dictionary of arguments
   for key, value in kwargs.items():

       # printing key and ValuesView
       print(key, value)

# calling function
main(one="One", two="Two",three= "three",four= "Four", five="Five")

Output:

the key-values are:
one One
two Two
three three
four Four
five Five

We can also add the keys separately and values separately. See the following example.

# Python kwargs function
def main(**kwargs):

   # variables
   keys = ""
   values = ""

   # iterating over dictionary of arguments
   for key, value in kwargs.items():

       # adding keys and values to the variables
       keys+=key
       values+=value

   # printing
   print("Added keys: {}".format(keys))
   print("Added values: {}".format(values))

# calling function
main(a="This ", b="is ", c="Python ", d="tutorial")

Output:

Added keys: abcd
Added values: This is Python tutorial

 

Understanding Python args

Unlike **kwargs, Python args is represented by a single asterisk like this; *args. Python args can be used a parameter to send a non-keyworded variables arguments in form of tuple to the function.

Advertisement

See the simple syntax of python args.

def main(*args):
<function statements>

 

Examples using Python args

Now let us see the python *args type by printing out the type using the python type function. See the example below:

# Using args in python function
def main(*args):

   # printing python args type
   print(type(args))

# calling function  
main()

Output:

<class 'tuple'>

Notice that the type of python args is a tuple. Now let us provide a element of tuple as arguments in the following example:

# Using args in python function
def main(*args):

   # printing python args
   print(args)

# calling function  
main(1, 2, 3, 4, 5)

Output:

(1, 2, 3, 4, 5)

 

Examples of python **kwargs and *args together

Now we are familiar with python kawargs and python args, so we can use them together as well. See the example below:

# Using **kwargs and *args together in python function
def main(*args,**kwargs):

   # printing args
   print("args: ", args)

   # printing python kwargs
   print("kwargs: ", kwargs)

# Now we can use both *args ,**kwargs
# to pass arguments to this function :
main('This','is','Python', "tutorial",a="Welcome",b="to",c="python", d="tutorial")

Output:

args: ('This', 'is', 'Python', 'tutorial')
kwargs: {'a': 'Welcome', 'b': 'to', 'c': 'python', 'd': 'tutorial'}

Note that the position of python kwargs and args is very important when we used them together.

We should use python args before than python kwargs. If we place python kwargs before python args, we will get error. See the following example.

# Using **kwargs and *args together in python function
def main(**kwargs,*args):

   # printing args
   print("args: ", args)

   # printing python kwargs
   print("kwargs: ", kwargs)

# Now we can use both *args ,**kwargs
# to pass arguments to this function :
main(a="Welcome",b="to",c="python", d="tutorial",'This','is','Python', "tutorial")

Output:

Advertisement
        def main(**kwargs,*args):
                                        ^
SyntaxError: invalid syntax

Learn python *args and **kwargs with simple examples

Python kwargs always takes the last position in the argument place. And when we try to place it before other arguments, we will get SyntaxError as shown above.

 

Summary

Sometimes in Python, we may come to a situation where we are not sure how many arguments will be provided by the user or the program. Maybe the arguments depend on any other processing which we are not sure about, in such cases python kwargs help us to solve the problem. **kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary. So a python kwargs allows us to pass any number of arguments in key value form ( dictionary). In this tutorial, we learned about python kwargs, from simple syntax to real examples. We come across various different cases and solve the problems using the python kwargs method. Moreover, we also learned the difference between python kwargs and python args and solve related problems.

 

Further Reading

python kwargs
python kwargs and python args
Python documentation

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment