Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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