codewithjohn.dev
Published on

How To Use *args and **kwargs In Python

In this article, we will explore how to use *args and **kwargs effectively in Python, along with several code examples to illustrate their usage.

Table of Contents

Functions are reusable blocks of statements performing a specific task. A function can also have arguments. However, there might be situations when you are not aware of the total number of arguments required. In Python, *args  and **kwargs are special syntaxes that allow you to pass a number of arguments to a function. *args is used to pass a variable number of non-keyworded arguments, while **kwargs is used to pass a variable number of keyworded arguments.

Using *args In Python

In Python, the *args syntax is used to pass a number of non-keyworded arguments to a function. It is represented by an asterisk (*) followed by a parameter name. By convention, we use the name args, but the name can be anything. It will work as long as we have a (*) before it.

Consider a situation where you need to write a function that calculates the total cost of items in a shopping cart. The items in the cart can have different prices, and you want the flexibility to pass any number of items to the function.

If you want to achive this without *args and **kwargs, you need to define the function with a fixed number of parameters, which can be limiting. Here's an example:

def calculate_total(item1_price, item2_price, item3_price):
    total = item1_price + item2_price + item3_price
    return total

total_cost = calculate_total(10, 20, 30)
print(total_cost)  # Output: 60

In the example above, we define a function called calculate_total that accepts a limited number of arguments. This approach becomes very difficult if the number of items in the shopping cart is variable, so we need to modify the function so it can accept any number of arguments.

Now, let's see how *args can make the function more flexible.

def calculate_total(*args):
    total = sum(args)
    return total

total_cost = calculate_total(10, 20, 30, 30)
print(total_cost)  # Output: 90

In the above example, we define the calculate_total function with *args, which allows us to pass any number of item prices as arguments.

Using **kwargs In Python

In Python, the **kwargs syntax is used to pass a number of keyworded arguments to a function. It is represented by an asterisk (**) followed by a parameter name. By convention, we use the name "kwargs", but the name can be anything. It will work as long as we have a (**) before it. Here's an example:

Now, let's consider a situation where we want to associate each item with a specific quantity for the above example.

Here's where **kwargs becomes useful:

def calculate_total(**kwargs):
    total = 0
    for item, (price, quantity) in kwargs.items():
        print(quantity)
        total += price * quantity
    return total

total_cost = calculate_total(item1=(10, 5), item2=(20, 3), item3=(30, 2))
print(total_cost)  # Output: 170

In this example, we define a function called calculate_total that accepts keyworded arguments. Each value in kwargs is a tuple containing the quantity and price of the item. We used tuple unpacking to assign the quantity and price to separate variables, then the total cost is calculated by multiplying the quantity with the price.

Using *args and **kwargs together:

You can use *args and **kwargs together in a function to accept a combination of non-keyworded and keyworded arguments. Here's an example:

def my_function(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

my_function(1, 2, name="John", age=25)
1
2
name John
age 25

In this example, we define a function called my_function that accepts both non-keyworded and keyworded arguments. We print the non-keyworded arguments using *args and the keyworded arguments using **kwargs.

Passing *args and **kwargs to another function:

You can also pass *args and **kwargs to another function. Here's an example:

def my_function(*args, **kwargs):
    another_function(*args, **kwargs)

def another_function(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

my_function(1, 2, name="John", age=25)
1
2
name John
age 25

In this example, we define two functions: my_function and another_function. my_function accepts *args and **kwargs and passes them to another_function, which then prints the arguments and keyworded arguments.

Conclusion

In this article, we explored two special keywords in Python *args and **kwargs, which makes a Python function flexible so it can accept a variable number of non-keyworded arguments and keyword arguments with the help of an example to show their usage and benefits. After reading this article, I hope you feel confident about using *args and **kwargs in your Python programs. Happy coding!

Like what you are reading?