What are *args and **kwargs?

These structures are sometimes used when we do not know the number of parameters to import or the number of parameters varies. Thus, we bring dynamism to our function. Let’s show it with an example; For example, let’s write a function that sums the entered numbers.

def add(number1, number2):
    print(sum([number1, number2]))
 
add(6, 9)

It works very well, so let’s add another number, this time add three numbers.

def add(number1, number2):
    print(sum([number1, number2]))
 
add(6, 9, 1)
TypeError: add() takes 2 positional arguments but 3 were given

Yes, we got an error because we stated that it can take two parameters while writing the function, so let’s fix it.

def add(number1, number2, number3):
    print(sum([number1, number2, number3]))
 
add(6, 9, 1)

This is how we fixed it. This is not a correct usage because if I want to add two numbers together again, I will have to change the function again. The function I wrote here is just a function that adds two numbers, but I don’t want that. I want to add 2 when I want and 10 when I want. Then we will use *args and **kwargs structures.

Using *args

def add(*args):
    print(sum(args))
 
add(6, 9, 1)
add(6, 9, 1, 10, 14)

# 16
# 40

You can now enter as many numbers as you want. No matter how many numbers the function gets, it will do the necessary operations.

Using **kwargs

Yes, we learned what *args is and how to use it. But what is **kwargs? And what is the difference between them? Likewise, we use **kwargs in situations where we do not know how many parameters to use, but **kwargs is based on a key value relationship. Did you remember this from somewhere because this is nothing but the dictionary data type we are talking about. Let’s show it with an example.

def printOutput(**kwargs):
    print(kwargs)
 
printOutput(number1 = 6, number2 = 9, number3 = 1) 
 
# {'number1': 6, 'number2': 9, 'number3': 1}

As you can see, it returned us a dictionary data type as output.

Combining *args and **kwargs

Well, you have a question, can I use *args and **kwags parameters? Let’s see now;

def printOutput(*args,**kwargs):
    print(kwargs)
    print(args)
 
printOutput(6, 9, 1, number = 6, number2 = 9, number3 = 2) 
 
# {'number': 6, 'number2': 9, 'number3': 2}
# (6, 9, 1)