You may find *args parameter in some python functions, how to use it? In this tutorial, we will use an example to introduce it for python beginners.
Look at this example:
def test_args(first, *args): print('Required argument: ', first) print(type(args)) print(args) for v in args: print ('Optional argument: ', v)
There is a *args parameter in python test_args function.
Run this function.
test_args(1, 2, 3, 4, 5)
You will get the result:
Required argument: 1 <class 'tuple'> (2, 3, 4, 5) Optional argument: 2 Optional argument: 3 Optional argument: 4 Optional argument: 5
From the result we can find:
- *args can allow us to pass variable length parameters to python function, which is very useful if we can not determine the number of parameters.
- args is a python tuple, all variable length parameters are saved in it.
- We can get each parameter args by index.
args is a python tuple, however, we can not run test_args like this:
test_args(1, (2, 3, 4, 5))
Run this code, you will find this result:
Required argument: 1 <class 'tuple'> ((2, 3, 4, 5),) Optional argument: (2, 3, 4, 5)
(2, 3, 4, 5) is a python tuple, it is regarded as a parameter and saved in args as an element.
We should notice, the args is only the name of parameter, we can change it to other name.
For example, we can change *args to *_ , which is the same.
def test_args(first, *_): print('Required argument: ', first) print(type(_)) print(_) for v in _: print ('Optional argument: ', v) test_args(1, 2, 3, 4, 5)
Run this code, we also can get the result below:
Required argument: 1 <class 'tuple'> (2, 3, 4, 5) Optional argument: 2 Optional argument: 3 Optional argument: 4 Optional argument: 5