Python *args & **kwargs in depth
python args and kwargs

Python *args & **kwargs in depth

By Chanh Ha | Python Geeks | 20 Apr 2020

Today, in Python explained, we are welcome to see one of the most mysterious things with a new Python learner. It is *args and **kwargs variables. We will figure out below questions:

  • What is *args and **kwargs variables?
  • When SHOULD and SHOULD NOT use *args and **kwargs
  • The * and ** (asterisk) operators in *arg and **kwargs

By answering questions, we step by step to understand these two special variables. And I strongly believe that you will be confident to use it in your next project.

What is *arg?

*args represents for arguments , it means we can pass many arguments to a function within only one variable *args*args will be parsed as a list of arguments and store in args variable.

This variable is especially useful when you define a function but not sure how many arguments you will receive. Take a look example below to get clear *args

def arg_func(*args):
    for arg in args:

# Yellow
arg_func("Yellow", "Green", "Black")
# Yellow
# Green
# Black

As you can see by running the example, no matter the number of argument was passed, the function still run expectedly. So remember this handy syntax and use it effectively.

What is **kwarg?

**kwargs represents for keyword arguments. It means the function will allow us to pass many keyword variables a time. Therefore, the input **kwargs will be parsed as a dictionary instead of a list such as *args.

This variable also useful when you don’t know how many keywords you should define in function. Or there is a large number of keyword variables that will be passed to function.

The example below will show you how to use **kwarg:

def kwarg_func(**kwargs):
    for key, value in kwargs.items():
        print("Key: {}. Value: {}".format(key, value))

# Key: name. Value: Yasuo
kwarg_func(name="Yasuo", age=21, city="SG")
# Key: name. Value: Yasuo
# Key: age. Value: 21
# Key: city. Value: SG

When SHOULD and SHOULD NOT use *args and **kwargs

Want to create a flexible function

Take advantage of *args and **kwargs will help you create a flexible function. You don’t have to define the number of arguments and its name as usual.

A Large number of arguments

It will be fine if our function has 2 or 3 arguments such as def new_func(name, age). However, if there are 20 arguments to be defined in a function such as def new_func(name, age, city, provine, phone, experiences, major, university,...), this time we should use *arg and **kwargs to shorten it.

Be aware when using *args and **kwargs

Nobody can’t refuse *arg and **kwargs useful, but remember that it cost you the readability. Obviously, when reading code, the function like def new_func(name, age) will easier to understand that def new_func(*args).

Furthermore, when coding the body of a function, it is easy to get an unexpected error if calling or using the variable that not exists in the **kwargs.

*arg and **kwargs have its own cons and pros, so be aware when using it. Don’t overuse it and have to trade by your code quality.

The * and ** (asterisk) operator in *arg and **kwargs

Some of the beginners think about it as a special mark that Python uses to recognize special variables like *arg and **kwargs. Actually, * and ** are the unpacking operator that help you. In short, it unpacked the values from iterable in Python.

Example of *:

>>> A = [1, 2, 3]
>>> print(*A)
1 2 3

Example of **:

>>> B = {"name": "Yasuo", "age": 29}
>>> C = {"city": "SG"}
>>> {**B, **C}
{'name': 'Yasuo', 'age': 29, 'city': 'SG'}

We can use * with a string:

>>> [*"Python Geeks"]
['P', 'y', 't', 'h', 'o', 'n', ' ', 'G', 'e', 'e', 'k', 's']


You now fully understand and ready to use *arg and **kwargs in your next project. Just keep in mind that there is no perfect solution, we want useful stuff, it can cost us readability. Be aware and use it effectively based on your real situation.

We would take a look at what we have been walking through:

  • What is *args and **kwargs variables?
  • When SHOULD and SHOULD NOT use *args and **kwargs
  • The * and ** (asterisk) operators in *arg and **kwargs

As a beginner, we recommend you other useful posts at Python Geeks:

The post Python *args & **kwargs in depth appeared first on Python Geeks.

Python Geeks
Python Geeks

Python is a one of the most popular programming language. Look back the time that I have just started to learn Python, it's not an easy time. Therefore, I would like to start this blog for sharing what I've learned, what I think and how Python impact my career. I would like to post some tips or best practice in Python as well. And it will be great if these blogs can help the audiences. Don't hesitate to tip me, like, share and comment to help me improve day by day.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.