Python *args and **kwargs

Functions are building blocks in Python. They take zero or more arguments and return a value.The *args and **kwargs make it easier and cleaner to handle arguments.we can pass a variable number of arguments to a function using special symbols. There are two special symbols:

1.) *args (Non-Keyword Arguments)

2.) **kwargs (Keyword Arguments)

a) *args:

when you not sure about the no. of arguments that can passed the function.Python have *args which allow to pass the variable no. of non keyword arguments to function.

def myFun(*argv):  
    for arg in argv:  
        print (arg) 
myFun('this', 'is', 'a', 'text') #this is a text

b) **kwargs:

**kwargs allow a function to take any number of keyword arguments.

def arg_printer(a, b, option=True, **kwargs):
   print(a, b)

arg_printer(3, 4, param1=5, param2=6)
3 4
{'param1': 5, 'param2': 6}

Some Advance examples of *Args and **Kwargs :

def argsKwargs(*args, **kwargs):
argsKwargs('1', 1, '', vote='yes', is_true=True, test=1, suff_example=True)

('1', 1, '')
{'vote': 'yes', 'is_true': True, 'test': 1, 'suff_example': True}
def numbe(*num):
    sum = 0
    for n in num:
        sum = sum + n



Sum: 8
Sum: 22
Sum: 17
def dataIntro(**data):
    print("\nData type of argument:",type(data))

    for key, value in data.items():
        print("{} is {}".format(key,value))

dataIntro(Firstname="Mark", Lastname="smith", Age=22, Phone=00000000)
dataIntro(Firstname="John", Lastname="wick", Email="", Country="Wakanda", Age=21, Phone=12346788)

Data type of argument: <class 'dict'>
Firstname is Mark
Lastname is smith
Age is 22
Phone is 00000000

Data type of argument: <class 'dict'>
Firstname is John
Lastname is Wick
Email is
Country is Wakanda
Age is 21
Phone is 12346788

if you like the article share with your friends.if you have any question or query related to article and have an any suggestions please leave in comment box.

Thanks for reading the Article.

Leave a Reply

Your email address will not be published. Required fields are marked *