Home »
Python
Multiple Function Arguments in Python
Python *args and **kwargs: In this tutorial, we are going to learn about the multiple function argument in Python programming language with examples.
Submitted by Sapna Deraje Radhakrishna, on November 22, 2019
The *args and **kwargs is an approach to pass multiple arguments to a function. They allow to pass a variable number of arguments to a function. However, please note it is not necessary to name the variables as *args or **kwargs only. Only the * is important. We could also name the variables as *var or **named_vars.
Usage of *args
*args is used to send a non-keyworded variable length argument list to a function.
Example:
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def test_args(arg1, *argv):
... print("first argument :{}".format(arg1))
... for arg in argv:
... print("argument received :{}".format(arg))
...
>>> test_args('test1', 'test2', 'test3')
first argument :test1
argument received :test2
argument received :test3
>>>
Usage of **kwargs
**kwargs allows to pass keyworded variable length arguments to a method. The **kwargs is used in order to handle named arguments in a function.
Example:
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def welcome_names(**kwargs):
... if kwargs:
... for key, value in kwargs.items():
... print("{} = {}".format(key, value))
...
>>> welcome_names(name="include_help")
name = include_help
>>>
Example:
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def test_multiple_args(arg1, arg2, arg3):
... print(arg1)
... print(arg2)
... print(arg3)
...
>>>
Now, let's use *args for the above function,
>>> args = ['test1', 1,2]
>>> test_multiple_args(*args)
test1
1
2
Now, using **kwargs,
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_multiple_args(**kwargs)
5
two
3
>>>
Python Tutorial
ADVERTISEMENT
ADVERTISEMENT