Variable length arguments in Python

Sept. 28, 2022, 7:48 a.m.


...

In some situations, it is not known in advance how many arguments will be passed to a function. In such cases, Python allows programmers to make function calls with arbitrary (or any) number of arguments. When we use arbitrary arguments or variable-length arguments, then the function definition uses an asterisk(*) before the parameter name.

In some situations, it is not known in advance how many arguments will be passed to a function. In such cases, Python allows programmers to make function calls with arbitrary (or any) number of arguments. When we use arbitrary arguments or variable-length arguments, then the function definition uses an asterisk(*) before the parameter name.

To check the data type of variable length argument.

def func1(*check):
    print(type(check))

if __name__=="__main__":
    name=["Jai","Ankit","Nishant"]
    func1(*name)

 Output:

<class 'tuple'>

Example of Variable length arguments:

def func(name, *fav_sub):
    print(f"\nSubjects selected by {name}")
    for item in fav_sub:
        print(item)
        
        
if __name__=="__main__":
    func("Jaikrishna","Python","C++","Data Analytics")
    func("Vishal","Data Structures")
    func("Deepak")

Output:

Subjects selected by Jaikrishna
Python
C++
Data Analytics

Subjects selected by Vishal
Data Structures

Subjects selected by Deepak

In the above program, in the function definition we have two parameters - one is name and the other is variable length parameter fav_sub. Every function call can have any no. of fav_sub and some can even have none.

Keyworded Arguments (**kwargs)

Python uses args to provide a variable-length non-keyword argument to a function, but it cannot be used to pass a keyword argument. kwargs, a Python solution for this problem, is used to pass the variable length of keyword arguments to the method.

Arguments are supplied in the dictionary, which creates a dictionary within the method with a name similar to the parameter.

Example of Keyworded arguments:

def func2(name,*args,**kwargs):
    print(f"Name of the Team: {name}")
    for members in args:
        print(members)
    
    print("\nRole assigned to team members:")
    for key, value in kwargs.items():
        print(f"{key} is {value}")

if __name__=="__main__":
    name="Mumbai Indians"
    players=["Rohit","SKY","Ishan","Bumrah","KP"]
    role={"Rohit":"Captain/Opener","SKY":"Middle order Batsman","Ishan":"WK/Opener","Bumrah":"Fast Bowler","KP":"Finisher"}
    func2(name,*players,**role)

Output:

Name of the Team: Mumbai Indians
Rohit
SKY
Ishan
Bumrah
KP

Role assigned to team members:
Rohit is Captain/Opener
SKY is Middle order Batsman
Ishan is WK/Opener
Bumrah is Fast Bowler
KP is Finisher

Points to remember:

  • The arbitary number of arguments passed to the function basically forms a tuple.
  • for loop is used to access the argumetns.
  • Variable length arguments if present in the function definition should be the last in the list of formal paramenters.
  • After variable length arguments must be keyword arguments only.

Using args and kwargs to Call a Function

def func3(a,b,c):
    print(f"{a}+{b}+{c}",a+b+c)

if __name__=="__main__":
    l=[5,6,7]
    func3(*l)
  
    k={"a":56,"b":57,"c":55}
    func4(**k)

 



Tags


Comments