Understanding Args and Kwargs in Python

In this tutorial, I will be focusing on arguments (*args) and keyword arguments (*kwargs) in Python.

I will teach you what args and kwargs are and, most importantly, how to use them—that is how
to take in an unlimited number of arguments and keyword arguments in functions.

What
Are Args?

*args are used to pass non-keyword
arguments. Examples of non-keywordarguments are fun(3,4), fun("foo","bar").

*args are usually used as a measure to prevent the
program from crashing if we don’t know how many arguments will be passed to
the function. This is used in C++ as well as other programming languages.

What Are Kwargs?

**kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.

An example of a keywordargument is fun(foo=2,bar=7).

**kwargs are just like *args except
you declare the variables and the amount within the function arguments.

Where to Use Args and Kwargs

Args and kwargs are useful when you want to:

Reduce code rewriting.

Make your code readable.

Reuse your code

Using
Args and Kwargs in Functions

Let's look at how kwargs and args are used in functions.

Args

The function below
takes in three arguments. The three arguments have been explicitly defined, so
any more or less will cause an error in the program.

def add(a, b,c):
print(a+b+c)
print add(2,3,4)

Let's run the function. The function will add the three numbers, giving the following output:

Output
9

What if we were to pass four arguments in the function instead of the required three? We will receive an error as shown below.

This is because only three parameters were defined in the function, but we have passed four positional arguments when calling the function.

def add(a, b,c):
print(a+b+c)
print add(2,3,4,5)

Output
TypeError: add() takes 3 positional arguments but 4 were given

In the second example below, the * is for non-keyword arguments and gets passed into the function. Instead of having defined arguments, we replace a, b and c with a single parameter (*args).

Notice how the use of *args makes it easy to use any number of arguments without having to change your code. *args provide more flexibility to your code since you can have as many arguments as you wish in the future.

def add(*args):
total = 0
for arg in args:
total+=arg
print total

Scenario 1
print add(1,2,5)
Output
8

Scenario 2
print add(1,2,5,6)
output
14

Scenario 3
print add(1,2,5,8)
Output
16

More Examples

Create a simple function as shown:

def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg

Test the function using a combination of integers and strings:

def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg
print func(11,3,4,5,"tuts")

Output
11
3
4
5
tuts

What if we were to pass a list as an argument? Test the function with a
list by replacing the previous arguments with a list, l = [11,3,4,5,"tuts].

def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print arg
l = [11,3,4,5,"tuts"]
print func(l)

This prints the list as a whole,
This is because its interpreting the list as one item.
Output
[11,3,4,5,"tuts]

From the above example, you can also use *args to unpack arguments that are already in a list or a tuple so that all elements
in the list are passed as different parameters.

Using the same function:

def func(*args):
# *args means for however many arguments you take in, it will catch them all
for arg in args:
print(arg)
l = [11,3,4,5,"tuts"]
print(func(*l))

Kwargs can be used for unpacking dictionary key,
value pairs. This is done using the double asterisk notation (**). It's important to note that each key must be matched with a value.

Here's a typical example of how it's done. The function below takes countries as keys and their capital cities as the values. It then prints out a statement which iterates over the kwargs and maps each keyword to the value assigned to it.

def capital_cities(**kwargs):
# initialize an empty list to store the result
result = []
for key, value in kwargs.items():
result.append("The capital city of {} is {} .format (key,value)
return result

Conclusion

*args and **kwargs are special syntax that are used in functions to pass a
variable number of arguments to a function.

*args occur before **kwargs in a function definition.

*args and **kwargs are best used in situations where the number of inputs will remain relatively small.

You can use any name you want; args and kwargs are only by convention and not a requirement. For example, you can use *foo instead of *args or **foo instead of **kwargs.

The official Python documentation offers a lot of information for further study. Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.