What are *args and **kwargs in Python and How to Use them

In this article, we will learn about Python *args and **kwargs, their uses, and functions with examples.

We define a function in programming to create reusable code that performs similar tasks. To conduct that action, we call a function with a specified value, which is referred to in Python as a function argument.

Suppose we’re creating a function to add three integers.

Example 01: Function to add 3 numbers

# Welcome to softhunt.net
def adder(x,y,z):
    print("sum:",x+y+z)

adder(78,34,12)

Output:

sum: 124

The adder() function in the above program takes three arguments: x, y, and z. When three numbers are sent to the adder() function, the result is the total of the three numbers.

Let’s see what happens when we pass more than 3 arguments in the adder() function.

Example 02:

# Welcome to softhunt.net
def adder(x,y,z):
    print("sum:",x+y+z)

adder(67,34,67,21,5)

Output:

Traceback (most recent call last):
  File "<string>", line 5, in <module>
TypeError: adder() takes 3 positional arguments but 5 were given

In the above program, we passed 5 arguments to the adder() function instead of 3 arguments due to which we got TypeError.

Introduction to *args and **kwargs in Python

In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:

  1. *args (Non-Keyword Arguments)
  2. **kwargs (Keyword Arguments)

When we’re not sure how many arguments to give into a function, we utilize *args and **kwargs as arguments.

Python *args

We don’t know how many arguments can be pass to a function, just as we don’t know how many arguments can be pass to a function in the previous example. A *args are a feature of Python that allows us to pass a variable number of non-keyword arguments to a function.

To provide variable-length parameters, we need to use an asterisk * before the parameter name in the function. The parameters are pass as a tuple, and inside the function, these passed arguments form a tuple with the same name as the parameter, except the asterisk *.

Example 03: Using *args to pass the variable-length arguments to the function

# Welcome to softhunt.net
def adder(*num):
    sum = 0
    
    for n in num:
        sum = sum + n

    print("Sum:",sum)

adder(5,8)
adder(6,7,8,9)
adder(11,12,13,14,15)

Output:

Sum: 13
Sum: 30
Sum: 65

We utilized *num as a parameter in the above program, which allows us to give a variable-length argument list to the adder() function. We have a loop within the method that adds the provided input and outputs the result. As a parameter to the function, we passed three separate tuples of varying lengths.

Python **kwargs

Python uses *args to send a variable-length non-keyword argument to a function, but we can’t use it to give a keyword argument. A **kwargs, a Python solution for this problem, allows us to provide the variable length of keyword arguments to the function.

To indicate this type of argument, we use a double asterisk ** before the parameter name in the function. The arguments are passed as a dictionary. Which creates a dictionary within the function with the same name as the parameter except for the double asterisk **.

Example 04: Using **kwargs to pass the variable keyword arguments to the function

# Welcome to softhunt.net
def intro(**data):
    print("\nData type of argument:",type(data))

    for key, value in data.items():
        print("{} is {}".format(key,value))

intro(Firstname="Ranjeet", Lastname="Kumar", Age=22, Phone=1122334455)
intro(Firstname="Softhunt", Lastname=".net", Email="[email protected]", Country="Pakistan", Age=22, Phone=1122334455)

Output:

Data type of argument: <class 'dict'>
Firstname is Ranjeet
Lastname is Kumar
Age is 22
Phone is 1122334455

Data type of argument: <class 'dict'>
Firstname is Softhunt
Lastname is .net
Email is [email protected]
Country is Pakistan
Age is 22
Phone is 1122334455

We have a function intro() with the parameter **data in the above program. The intro() function was passed through two dictionaries with variable argument lengths. Inside the intro() function, we have a for loop that works with the data of the passed dictionary and outputs the value of the dictionary.

*args and **kwargs: Conclusion

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 arguments and keyword arguments.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Python Tuple [With Examples]

Leave a Comment