Social Media

2/05/2019

Variable length arguments

Variable length arguments:
If a function has variable length arguments, it means it has the capability to accept any number of arguments.
Variable length argument is prefixed with *.
The type of variable length argument is tuple.

Write a function which can return the sum of any number of arguments passed to it.
def f1(*a):
    return sum(a)

print(f1(2)) # 2
print(f1(2,3)) # 5
print(f1())  # 0


Note* In this case keyword argument is compulsory to set the value of second argument.
def f1(*m,s):
    print(m,s) # (2, 3, 4) 5

f1(2,3,4,s=5)


Variable length keyword arguments:
If we write ** then its type will be dictionary.
It always accepts keyword arguments.
If positional arguments are passed to it, it will shows error.

def f1(**x):
    print(x)

f1(a=2,b=3) # {'a': 2, 'b': 3}
f1(a=1,b=2,c=3) # {'a': 1, 'b': 2, 'c': 3}

f1(a=1,a=2) # will show error
Be First to Post Comment !
Post a Comment