Args and Kwargs in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Args and Kwargs in Python?

I have watched lots of Python tutorials and the keywords "args" and "kwargs" are used often but I'm unsure of their use? Can anyone comment what they are and how they can be used? Note: I haven't finished the Python course completely so they may be in the course but I have not learned about them yet! Thanks! :)

25th Jul 2017, 3:39 PM
Thomas John
Thomas John - avatar
3 Answers
+ 6
*args is used when you're not sure how many arguments will be passed to your function. >>> def f(arg1, *args): print(arg1) print(args) >>> f(1,2,3,4,5,6) 1 (2, 3, 4, 5, 6) So if you have a required argument arg1, the first argument you pass to the function will be arg1, and the rest (no matter how many) will be a part of a tuple *args, which can be unpacked inside the function and used as needed. Kwargs is a dictionary of keyword arguments that is passed to the function as a dictionary: >>> def f(arg1, *args, **kwargs): print(arg1) print(args) print(kwargs) >>> f(1,2,3,4,5,6, keyword_arg_1 = 1, keyword_arg_2 = 2) 1 (2, 3, 4, 5, 6) {'keyword_arg_1': 1, 'keyword_arg_2': 2} Hope this clears it up (:
25th Jul 2017, 4:25 PM
Maya
Maya - avatar
+ 1
Thanks that's really helpful! 😃
25th Jul 2017, 4:26 PM
Thomas John
Thomas John - avatar
+ 1
Here is my primer on *args in Python - hope you find it useful! https://code.sololearn.com/cce88fWlK7L7/?ref=app
26th Apr 2018, 6:24 PM
Johannes
Johannes - avatar