How to Use *args and **kwargs in Python?

How to Use *args and **kwargs in Python?

ยท

2 min read

We can pass a variable number of arguments to a function by passing a parameter name with an asterisk(*) or double asterisk(**) like *args and **kwargs.

I've already covered *args with examples - Check it out Here.

Here, In this blog, I will cover **kwargs which stands for keyword arguments.

Giving a name to each value is called Keyword Argument. Ex, name="rc". When we want to pass variable-length keyword arguments to a python function, we can make use of **kwargs. The argument is then converted into a dictionary i.e the type of **kwargs is dictionary.

def person(**dict):
    print(dict, type(dict))
# passing dynamic keyworded values
person(name="Walter", nickName="Heisenburg")
person(name="White")

# Output-
# {'name': 'Walter', 'nickName': 'Heisenburg'} <class 'dict'>
# {'name': 'White'} <class 'dict'>

We can give any name to the parameter, like here, dict. It is the standard way to use kwargs as the parameter name and on which operation of a dictionary can be performed.

def totalItems(**kwargs):
    total = 0
    for value in kwargs.values():
        total += value
    return total
print(totalItems(a=5, b=20))

# Output-
# 25

If we want to pass a normal argument along with *args and **kwargs then we need to follow an order.

  1. Normal argument

  2. *args

  3. **kwargs

def person(id, *args, ** kwargs):
    print("ID is:", id)
    for key, value in kwargs.items():
        print("{} is: {}".format(key,value))
    for element in args:
        print("I'm a", element)

person(1, "Developer", name='RC')

# Output-
# ID is: 1
# name is: RC
# I'm a Developer

We can pass only one normal argument and else will be treated as keyword and non-keyword arguments.

ย