Python Object-Oriented Python Inheritance Multiple Superclasses

What's the difference between *args and *kwargs.

For **kwargs i got it any extra variables or input create a dict but what about *args why we use it.

1 Answer

adrian miranda
adrian miranda
13,189 Points

Well, **kwargs will wind up containing extra arguments that you give, where the arguments have a keyword. By contrast, *args will contain extra positional arguments, that don't have a keyword name.

Perhaps an example will make it more obvious. Suppose you define a function like this:

def example1(first, second, *args):
    print(f"first = {first}, second = {second}")
    print("args = {}".format(args)

If you called it as example1(1, 2, 3, 4), then 1 and 2 would be inserted into first and second, and args would be a set containing 3 and 4. So *args permits you to give extra positional arguments, without a keyword.

By contrast, here is how you might use both *args and **kwargs:

def example2(first, second, *args, **kwargs):
    print(f"first = {first}, second = {second}")
    print("args = {}".format(args))
    print("kwargs = {}.format(kwargs))

Then you could call it as example(1, 2, 3, 4, hobbit="bilbo"). As before, args will be a set containing 3 and 4. And now kwargs will be a dict containing {'hobbit': 'bilbo'}.