Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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'}.