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

Can someone help with kwargs and args?

Kenneth Love : I have recently gotten to including **kwargs and *args into my functions and I understand how to implement them into my code but the only part I am unsure about is the cases in which you'd use each. Are there certain situations in which I would use one over the other? Or can they be interchanged? If you could help me with this I would be very grateful.

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

*args is a tuple of ordered arguments where you're not sure of the number of them. **kwargs is a dict of keyword arguments where you don't know the number or the name.

Let's say I have a function that'll add together any number of numbers passed into it. I don't know how many numbers I'll get and they don't need names, so I'd use *args.

def sum(*args):
    total = 0
    for number in args:
        total += number
    return number

If I had a function, though, that needed to, say, collect a username, password, and then any extra details the user wanted to contribute, I could use **kwargs.

def create_user(username, password, **kwargs):
    user = User.new(username, password, extra_data=json.dumps(kwargs))