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 Python Collections (2016, retired 2019) Tuples Tuple Swapping

Akshaan Mazumdar
Akshaan Mazumdar
3,787 Points

What is the difference between *args and **kwargs I tried printing (*args) and (**kwargs) in the same function

def add(base,*args): total=base print(base) print("!!") for num in args: print(num) total= num+total

print("!!!")
print(total)

def add2(base,args,*kwargs): print("now printing add2 stuff") print(args) print(kwargs def main(): add(7) x=4 y=7 add2(6,6,8,9,x,y)

main()

1 Answer

Steven Parker
Steven Parker
231,236 Points

The names are not important, but "args" and "kwargs" are common conventions. The "*" operator gathers up individual arguments into a tuple, and the "**" operator gathers up keword/value arguments into a dictionary.

So if I define a function like this: "def splat(*args, **kwargs)", then inside the function, "args" will be a tuple with all the individual arguments that were passed (like "Joe" or 31), an "kwargs" will be a dictionary of the keyword pairs (like "age=21" or "color='blue'").