If you have ever needed to pass a variable number of arguments to a Python function you may have come across the *args and **kwargs syntax. These powerful tools allow you to pass a variable number of non-keyword and keyword arguments, respectively. In this post, lets dive into what *args and **kwargs are, how they work, and provide some examples to help you better understand these Python features.
What is *args?
It is a special syntax used in python function definition to pass a variable/unlimited number of non-keyword arguments to the function. Let’s use an example to make things more clear.
Example 1: Create a python function that takes in any number of values and sum all values passed to it.
def add(*args):
sum = 0
for arg in args:
sum += arg
print(f"The sum is: {sum}")
add(1,2,3,4,5,6,7,8,9)
Output: The sum is: 45
Example 2: Create a python function to display all car brand names passed to it.
def names(*args):
print("The car brands are:")
for arg in args:
print(arg)
names('Jeep','Volkswagen','Toyota','Ford','Rivian','Tesla')
Output:
The car brands are:
Jeep
Volkswagen
Toyota
Ford
Rivian
Tesla
What is **kwargs?
It is a special syntax used to pass keyword arguments to a function. These keyword arguments can be of any number just like in args. A keyword argument is where you give a name to the argument as you pass it to the function. Let’s use some examples to make things clear.
Example 1:
def names(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
names(Fname="John",Lname="Doe",work="Doctor")
Output:
Fname: John
Lname: Doe
work: Doctor
It is important to note that args and kwargs are just names and can be replaced with whatever names you like. What is important is the * and ** operators which are called unpacking operators. These operators must be included whenever you want to create such functions. To prove this, lets rename args and kwargs in the above examples.
Example 1:
def names(*cars):
print("The car brands are:")
for x in cars:
print(x)
names('Jeep','Volkswagen','Toyota','Ford','Rivian','Tesla')
Output:
The car brands are:
Jeep
Volkswagen
Toyota
Ford
Rivian
Tesla
Example 2:
def names(**names):
for key, value in names.items():
print(f"{key}: {value}")
names(Fname="John",Lname="Doe",work="Doctor")
Output:
Fname: John
Lname: Doe
work: Doctor
Why use *args and **kwargs.
These two python features are very useful in creating functions which the number of arguments to be provided is not known.
Conclusion
- *args passes a variable number of non-keyword arguments.
- **kwargs passes a variable number of keyword arguments.
- Keyword arguments are arguments that have a key and value. For example, fname=”name”
- The names args and kwargs can be changed to whatever you want, the most important part are the unpacking operators * and **.
Top comments (0)