Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How To Use *args and **kwargs In Python

3 min read

Functions are reusable a block of codes performing a specific task, they make the program more effective and modular.

While defining a function in Python, we also specify the parameters it can accept which we later pass as arguments in function call.

However, there might be situations when you are not aware of the total number of arguments required or you suspect that later on, the function may need additional arguments.

We can use the special syntax * args  and **kwargs within a function definition in order to pass any number of arguments to a function. In this article, we guide you on how to use *args and **kwars efficiently in Python.

*args In Python

In Python, *args is used to pass an arbitrary number of arguments to a function. It's worth mentioning that the single asterisk( * ) is the most important element, the word arg is just a naming convention we can name it anything it will work as long as we have a ( * ) before it.

This could be better understood by the following example, Let's create a function which can add numbers,

def total_sum(x, y):
    sum = x + y
    print(sum)

total_sum(3,4)

This simple function adds the two number which we pass in the function call. But what if we want to add three numbers?

Unfortunately passing three arguments in function call will lead to an error.

def total_sum(x, y):
    sum = x + y
    print(sum)

total_sum(3,4,2)

Output:

TypeError: total_sum() takes 2 positional arguments but 3 were given

The *args parameter is helpful in tackling such programming issues. Using  *args parameter gives the function ability to accepts any number of positional arguments.

def total_sum(*args):
    sum = 0
    for num in args:
        sum += num
    print("Sum :", sum)

total_sum(3, 4)
total_sum(3, 6, 7, 8,2)
total_sum(3, 7, 8,2)
total_sum(3, 8, 9)

Output:

Sum : 7
Sum : 26
Sum : 20
Sum : 20

Now we can pass as many arguments we wish and the function will work for all of them, this makes our code more modular and flexible.

As stated above the asterisk(*) is the most important syntax we can replace args with literally anything yet it will work.

def total_sum(*anything):
    sum = 0
    for num in anything:
        sum += num
    print("Sum :", sum)

total_sum(3, 4)
total_sum(3, 6, 7, 8,2)
total_sum(3, 7, 8,2)
total_sum(3, 8, 9)

Output:

Sum : 7
Sum : 26
Sum : 20
Sum : 20

Using **kwargs In Python

Keyword arguments allow passing arguments as parameter names. In order to design a function which takes an arbitrary number of keywords arguments **kwargs in used as a parameter. It's worth noting that the double astrick(**) is the key element here kwargs is just a convention you can use any word.

def print_kwargs(**kwargs):
    print(kwargs)

print_kwargs(a=1, b=2, c="Some Text")

Output:

{'a': 1, 'b': 2, 'c': 'Some Text'}

We received all the keywords and their values in a dictionary(Key: value) form and we can perform every dictionary operation on it. Note that dictionaries are unordered (On Python 3.5 and lower ) so your result may vary for a large dictionary.

Let's extend the function to perform some basic dictionary operations.

def print_kwargs(**kwargs):
    for key in kwargs:
        print("The key {} holds {} value".format(key, kwargs[key]))

print_kwargs(a=1, b=2, c="Some Text")

Output:

The key a holds 1 value
The key b holds 2 value
The key c holds Some Text value

Keywords arguments are making our functions more flexible.

In Python, we can use both *args and **kwargs on the same function as follows:

def function( *args, **kwargs):
    print(args)
    print(kwargs)

function(6, 7, 8, a=1, b=2, c="Some Text")

Output:

(7, 8)
{'a': 1, 'b': 2, 'c': 'Some Text'}


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read