Python *args and **kwargs


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.

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.

Now you can pass any number of arguments to the function like this,

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')

Expected Output:

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.

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

Note: For this to work 2 things are necessary:

  1. Names of arguments in function must match with the name of keys in dictionary.
  2. Number of arguments should be same as number of keys in the dictionary.

Other Tutorials

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!


2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
PythonGurumatt Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
matt
Guest
matt

def sum(*args):
s = 0
for i in args:
s += i
print(“sum is”, s)

This does not do what you say it does:

sum(1, 2, 3)
6

Instead, it counts the number of arguments passed.

PythonGuru
Admin

Check again, It is working fine. What’s the problem?