Functions are reusable blocks of code that perform a specific task; they make the program more efficient and modular.
When we define a function in Python, we also specify the parameters it can accept, which we then pass as arguments in the function call.
However, there may be instances where you are unaware of the total number of arguments required or suspect that the function will require additional arguments in the future.
To pass any number of arguments to a function, use the special syntax *args and **kwargs within the function definition. In this article, we will show you how to use *args and **kwars in Python efficiently.
*args In Python
In Python, the *args keyword is used to pass an arbitrary number of arguments to a function. It’s worth noting that the single asterisk (*) is the most important element; the word arg is simply a naming convention; we can call it whatever we want as long as we put a (*) before it.
This could be better understood by the following example, Let’s create a function which can add numbers,
def total_sum(x, y):
sum = x + y
print(sum)
total_sum(6,7)
This simple function adds the two number which we pass in the function call. But what if we want to add three numbers?
Unfortunately passing three arguments in function call will lead to an error.
def total_sum(x, y):
sum = x + y
print(sum)
total_sum(7,2,1)
#output
TypeError: total_sum() takes 2 positional arguments but 3 were given
The *args
parameter is helpful in tackling such programming issues. Using *args
parameter gives the function ability to accepts any number of positional arguments.
def total_sum(*args):
sum = 0
for num in args:
sum += num
print("Sum :", sum)
total_sum(4, 8)
total_sum(2, 5, 6, 4,4)
total_sum(9, 8, 4,1)
total_sum(6, 3, 5)
#output
Sum : 12
Sum : 21
Sum : 22
Sum : 14
Now we can pass as many arguments we wish and the function will work for all of them, this makes our code more modular and flexible.
As stated above the asterisk(*) is the most important syntax we can replace args with literally anything yet it will work.
def total_sum(*anything):
sum = 0
for num in anything:
sum += num
print("Sum :", sum)
total_sum(4, 8)
total_sum(2, 5, 6, 4,4)
total_sum(9, 8, 4,1)
total_sum(6, 3, 5)
#output
Sum : 12
Sum : 21
Sum : 22
Sum : 14
Using **kwargs In Python
Keyword arguments allow arguments to be passed as parameter names. To design a function that accepts an arbitrary number of keyword arguments, kwargs is used as a parameter. It is worth noting that the double astrick (**) is the key element here, kwargs is simply a convention; any word can be used.
def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(a=4, b=3, c="MrCoder701")
#output
{'a': 4, 'b': 3, 'c': 'MrCoder701'}
We received all of the keywords and their values in the form of a dictionary (Key: value), which allows us to perform all dictionary operations on it. Note that dictionaries are unordered (on Python 3.5 and lower), so your results may differ for a large dictionary.
Let’s extend the function to perform some basic dictionary operations.
def print_kwargs(**kwargs):
for key in kwargs:
print("The key {} holds {} value".format(key, kwargs[key]))
print_kwargs(a=4, b=3, c="MrCoder701")
#output
The key a holds 4 value
The key b holds 3 value
The key c holds MrCoder701 value
Keywords arguments are making our functions more flexible.
In Python, we can use both *args
and **kwargs
on the same function as follows:
def function( *args, **kwargs):
print(args)
print(kwargs)
function(2, 5, 4, a=7, b=5, c="MrCoder701")
#output
(2, 5, 4)
{'a': 7, 'b': 5, 'c': 'MrCoder701'}
Difference between *args
and **kwargs
in Python?
Aspect | *args | **kwargs |
What it is? | A way to pass multiple positional arguments. | A way to pass multiple keyword arguments. |
What it looks like | Like this: func(1, 2, 3) . You pass values by position. | Like this: func(a=1, b=2, c=3) . You pass values by name. |
How to access | Inside the function, it’s a tuple of values. | Inside the function, it’s a dictionary of values. |
When to use it | Use when the number of arguments isn’t fixed. Example? Maybe you want to add up numbers: add(1, 2, 3) . | Use when you need named arguments. Think: options or settings. Example? create_user(name="John", age=30) . |
Common scenario | Passing a bunch of numbers or strings. Like a list but easier. | Named parameters. Think forms or filters. Like search(query="shoes", limit=10) . |
Fun fact | You can combine it with regular arguments. Neat, right? | Same here. You can mix *args and **kwargs in one function. |
Quick takeaway | Positional arguments packed as a tuple. Use when you don’t care about names. | Keyword arguments packed as a dictionary. Use when names matter. |
*args
and **kwargs
in Python?*args and **kwargs in Python – FAQs
Why use *args
and **kwargs
in Python?
*args
and *
*kwargs
allow functions to accept a variable number of arguments:
*args
(arguments) allows you to pass a variable number of positional arguments to a function.**kwargs
(keyword arguments) allows you to pass a variable number of keyword arguments (key-value pairs) to a function.
Is *args
a list or tuple in Python?
def example_function(*args):
print(type(args)) # <class 'tuple'>
example_function(1, 2, 3)
*args collects additional positional arguments into a tuple, not a list. The arguments are accessible using tuple indexing and iteration.
Why use *args
instead of a list?
*args is used when you want to pass a variable number of arguments to a function without explicitly specifying each argument in a list. It allows for flexibility and simplicity when defining functions that may take an unknown number of arguments.
def sum_values(*args):
total = sum(args)
return total
result = sum_values(1, 2, 3, 4, 5)
print(result) # Output: 15
How to pass **kwargs
?
To pass keyword arguments (**kwargs) to a function, you provide key-value pairs when calling the function.
def example_function(**kwargs):
print(kwargs)
example_function(name='Alice', age=30)
Output:
{'name': 'Alice', 'age': 30}
Inside the function, kwargs
will be a dictionary containing the passed keyword arguments.
A Note From the Author
Thank you so much for taking the time to read the story. If you found my article helpful and interesting, please share your thoughts in the comment section, and don’t forget to share and clap
Let’s Get in Touch!
- YouTube: mrcoder701
- Instagram: mr_coder_701
- LinkedIn: Gajanan Rajput
- Website: mrcoder701.com
- GitHub: @gajanan0707
- Medium: Gajanan Rajput
That is the proper weblog for anyone who needs to search out out about this topic. You notice a lot its virtually onerous to argue with you (not that I truly would want…HaHa). You undoubtedly put a brand new spin on a subject thats been written about for years. Great stuff, simply nice!