How to Use *args and **kwargs in Python

Share Your Love

In this post, we’ll look at how to use *args and **kwargs in Python, as well as some examples.

We frequently need to supply values to a function when writing it. Function arguments are the names given to these items.

Function Arguments Have a Problem

Let’s create a Python method to add two numbers. Let’s put it this way:

def add(x, y):
    return x+y

print(add(2,3))

Output:

5

What if you need to multiply three numbers together? To make it even easier, we can change the function to accept three arguments and return the sum as:

def add(x, y, z):
    return x+y+z

print(add(2, 3, 5))

Output

10

Wasn’t that a piece of cake? It was, indeed!

But what if we only had to add two numbers this time? Will our modified function assist us in calculating the total? Let’s have a look:

def add(x, y, z):
    return x+y+z


print(add(2, 3))

Output:

Traceback (most recent call last):
  File "D:\Quarantine\Test\Blog-Codes\args-kwargs\main.py", line 14, in <module>
    print(add(2, 3))
TypeError: add() missing 1 required positional argument: 'z'

Do you see the issue?

When we have a variable number of parameters, we have an issue. Should we continue to tweak the code such that it accepts the exact number of arguments? No way, we’re not going to do that.

So there must be a different method to go about it. Here’s where *args and **kwargs come into play.

When you’re not sure how many arguments to provide into a function, you can use *args and **kwargs as arguments.

How to Use *args in Python

*args is a Python function that allows us to pass a variable number of non-keyword arguments. To pass a variable number of parameters, we need use an asterisk (*) before the parameter name in the function.

def add(*args):
    print(args, type(args))

add(2, 3)

Output:

(2, 3) <class 'tuple'>

As a result, we know that inside the function, these passed arguments form a tuple with the same name as the parameter excluding *.

Let’s now update our add() code to accept a variable number of inputs.

def add(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total


print(add(2, 3))
print(add(2, 3, 5))
print(add(2, 3, 5, 7))
print(add(2, 3, 5, 7, 9))

Output:

5
10
17
26

It’s worth noting that the name of the argument does not have to be args. It’s all about the numbers in this situation. However, using *args as the name is a common practice.

How to Use **kwargs in Python

**kwargs is a Python function that allows us to pass a variable number of keyword arguments. To indicate this type of argument, we use a double-asterisk (**) before the parameter name in the function.

def total_fruits(**kwargs):
    print(kwargs, type(kwargs))

total_fruits(banana=5, mango=7, apple=8)

Output:

{'banana': 5, 'mango': 7, 'apple': 8} <class 'dict'>

As a result, we can see that the arguments are supplied as a dictionary in this example and that these arguments form a dictionary inside the function with the same name as the parameter excluding **.

Let’s finish up the total_fruits() function and get the total number of fruits.

def total_fruits(**fruits):
    total = 0
    for amount in fruits.values():
        total += amount
    return total

print(total_fruits(banana=5, mango=7, apple=8))
print(total_fruits(banana=5, mango=7, apple=8, oranges=10))
print(total_fruits(banana=5, mango=7))
#Output:
 
20
30
12

It’s worth noting that the argument’s name does not have to be kwargs — it can be anything. It’s fruits in this case. However, using **kwargs as a name is a common practice.

Final Thoughts

We learned about two Python special keywords in this article: *args and **kwargs. These make a Python function flexible by allowing it to take a variable number of parameters and keyword arguments.

Thank you for taking the time to read this!

Share Your Love
Default image
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 343

Newsletter Updates

Enter your email address below to subscribe to our newsletter