Python *args and **kwargs
(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
What is *args ??
*args allows us to pass variable number of arguments to the function. Let’s take an example to make this clear.
Suppose you created a function to add two number like this.
12 | defsum(a,b): print("sum is",a+b) |
As you can see this program only accepts two numbers, what if you want to pass more than two arguments, this is where *args comes into play.
12345 | defsum(*args): s=0 foriinargs: s+=i print("sum is",s) |
Now you can pass any number of arguments to the function like this,
12345678 | >>>sum(1,2,3)6>>> |
Note: name of *args is just a convention you can use anything that is a valid identifier. For e.g *myargs is perfectly valid.
What is **kwargs ?
**kwargs allows us to pass variable number of keyword argument like this func_name(name='tim',team='school')
12345 | defmy_func(**kwargs): fori,jinkwargs.items(): print(i,j)my_func(name='tim',sport='football',roll=19) |
Expected Output:
123 | sport footballroll19name tim |
Using *args and **kwargs in function call
You can use *args to pass elements in an iterable variable to a function. Following example will clear everything.
12345 | defmy_three(a,b,c): print(a,b,c)a=[1,2,3]my_three(*a)# here list is broken into three elements |
Note: This works only when number of argument is same as number of elements in the iterable variable.
Similarly you can use **kwargs to call a function like this
12345 | defmy_three(a,b,c): print(a,b,c)a={'a':"one",'b':"two",'c':"three"}my_three(**a) |
Note: For this to work 2 things are necessary:
- Names of arguments in function must match with the name of keys in dictionary.
- Number of arguments should be same as number of keys in the dictionary.
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!