'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Dec 29, 2023
Easy

*Args and **Kwargs in Python

Author Rohit Kumar
0 upvote
gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Hello Ninjas, I hope you are familiar with the use of functions in our programs. And the different kinds of functions that a programming language provides us. Some functions work on the arguments or values that we provide to them. But do you know it is also possible to pass a variable number of arguments to our function? The answer is using args and kwargs. *args allows the passing of multiple non-keyworded arguments, enabling tuple operations. Meanwhile, **kwargs facilitates the use of multiple keyword arguments as a dictionary, supporting dictionary operations in functions.

Args and Kwargs in Python

In this article, we will learn about *Args and **Kwargs in Python in detail like how are they used to pass values to the functions so that they can use them for computation. So let's dive deep into the topic.

What are Arguments?

We can send a variable number of arguments to a function using Variable-length arguments (varags). We can use special symbols to pass variable number arguments to a function.

In Python there are two ways to define variable length parameters in Python.

  • Non-Keyworded Arguments (*args)
  • Keyworded Arguments (**kwargs)
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Need of *args and **kwargs in Python

We need *args and **kwargs in Python to handle the varying numbers of function arguments. *args lets you pass any number of positional arguments, while **kwargs accepts keyword arguments as a dictionary. This flexibility is valuable when you're unsure about the exact number of inputs or want to make your code more adaptable.

For example, consider a function that calculates the sum of numbers:

  • Python

Python

def calc_sum(*args):
res = 0
for i in args:
res += i
return res
ans = calc_sum(1, 2, 3, 4, 5)
print(ans)

 

Output

15

 

Here, *args allows us to sum an arbitrary number of values. And, **kwargs provides the flexibility for keyword arguments, which enhances Python's versatility.

What is *args in Python?

Args are used in Python to pass a variable number of non-keyworded arguments to a function. We use the symbol to use the non-keyworded arguments by appending the * symbol in the name of the parameters in the function definition statement. It makes that variable iterable; that is, we can use a for loop over that variable, and it assigns the arguments to that single variable preceded by the keyword *. The function receives the value and assigns them to the args variable in the form of a tuple. They are also called positional arguments. 

Example: The function is passed variable length arguments using *args.

Code:

  • Python

Python

def ninjaName(*args):
   print("The Name of the Ninjas are :")
   for x in args:
       print(x)


ninjaName("Rohit", "Ayushi")

 

Output:

The name of the Ninjas are :
Rohit
Ayushi

 

Explanation:

We have defined a function called ninjaName with a variable length parameter called args, denoted by *args. The asterisk * converts a simple variable into a list of strings. We print the values received by the args variable by iterating over it. In the main function, we pass two arguments to the ninjaName function, which are then printed by it.        

What is **Kwargs in Python?

Kwargs are used in Python to pass a variable number of keyword arguments to a function. We use a double asterisk before the parameter's name in the function definition statement to use keyword arguments in our program. We can think of keyworded arguments as a key-value pair. The key is the argument's name, and the value is the value we assign to it while passing to the function. The function is going to receive them in the form of a dictionary.

Example:

Code:

  • Python

Python

def ninjaName(**kwargs):
   print("The name of the Ninjas are :")
   for key, value in kwargs.items():
       print(f"{key} : {value}")
       
ninjaName(ninja1="Eren Yeager",ninja2="Darth Vader",ninja3="Chandler",ninja4="Monica")

 

Output:

The name of the Ninjas are :
ninja1 : Eren Yeager
ninja2 : Darth Vader
ninja3 : Chandler
ninja4 : Monica

 

Explanation:

We have defined a function called ninjaName with a variable length keyworded parameter called kwargs, denoted by *kwargs. The double asterisk ** converts a simple variable into a list of strings. We print the values received by the args variable by iterating over it. In the main function, we pass four key-value pairs as an argument to the ninjaName function, which is then printed by it. The function iterates over the variable kwargs by using the kwargs.item() function.  

Also see, Convert String to List Python

Unpacking Arguments with *args and **kwargs in Python

So far, we have discussed the working of args and kwargs.

Let’s consider the following piece of code:

  • Python

Python

def my_function(*args):
   for x in args:
       print(x)


args=[1,2,3,4]


print("Case 1")
print(my_function(args))
print("\n")


print("Case 2")
print(my_function(*args))

 

Output:

Case 1
[1, 2, 3, 4]


Case 2
1
2
3
4

 

Explanation-

We have defined a function my_function which takes a non-keyworded variable length argument and simply prints its value.

In the first case, we pass the entire tuple as an argument. The Function takes this tuple as a single argument and prints the entire tuple at once.

This is the normal working of *args in Python.

In case 2, we have done something called unpacking of argument. We have passed the list as an argument but have used the * symbol in the argument list. This tells the Python program that it has to unpack this variable, which means that each element of the tuple will be passed to the args variable in Function and individually accessible.

That is why all the elements are printed individually on a separate line. 

Pros and Cons of using args and kwargs in Python

Pros

Let us discuss some benefits of using args and kwargs in Python as follows:

  • Readability
    kwargs enhance the code readability by naming the arguments explicitly.
     
  • Flexibility
    args allow to handle a variable's number of positional arguments. kargs handle keyword arguments. It offers flexibility in designing the function.
     
  • Default Values
    kwargs allows to set default values for the parameters of the function. It improves the control over the parameters.

Cons

Let us discuss some limitations of using args and kwargs in Python as follows:

  • Errors
    If you misinterpret args and kwargs, it can result in errors, which can be hard to debug.
     
  • Complexity
    If you overuse args and kwargs, it can lead to a complex code, especially for beginner coders.
     
  • Performance
    If you use args and kwargs, they can introduce performance overhead compared to standard keyword and positional arguments.

Difference between keyworded and non-keyworded arguments

Keyworded and Non-keyworded arguments in Python have the following differences-

Non-Keyworded Arguments

Keyworded Arguments

It is indicated by putting an asterisk (*) before a parameter name in the list of parameters in the function definition.It is indicated by putting an asterisk (**) before a parameter name in the list of parameters in the function definition.
The readability of code is less as the passed arguments do not have a name associated with them.  The readability of code increases as the variable name is associated with value we pass to the function.  
Arguments are passed in the form of a tuple.Arguments are passed as dictionaries and are present as a key-value pair.

Frequently Asked Questions

What is the use of args and kwargs in Python?

*args allows the passing of multiple non-keyworded arguments, enabling tuple operations. Meanwhile, **kwargs facilitates the use of multiple keyword arguments as a dictionary, supporting dictionary operations in functions.

When should I use args and kwargs?

You should use args for positional arguments and kwargs for keyword arguments when writing Python functions to handle variable input parameters.

How do you use args and kwargs together?

To use args and kwargs together in Python, you can define a function with both parameters like this: "def the_function(*args, **kwargs):" This way both are used together.

Why use args instead of list?

We use args instead of list because it allows for flexible and cleaner code compared to lists since it can accept any number of positional arguments directly.

What is the best practice of args and kwargs?

The best practice is to use args for unspecified positional arguments and kwargs for keyword arguments with clear and descriptive variable names for better readability.

What is the difference between arguments and parameters in Python?

A parameter is the function definition's listed variable inside parentheses, while an argument is the value sent to the function during its call.

What is one difference and one similarity between args and kwargs in Python?

The difference between args and kwargs in Python is that args are used for sending non-keyworded arguments to the function, while kwargs are used to send keyworded arguments to the function. The Similarity is that both are used to send variable lengths of parameters to the function. 

Conclusion

Congrats, Ninja!! You've learned about the use of *Args and **Kwargs in Python and what is the difference between args and kwargs in Python. You also learned about what is the difference between arguments and parameters. We also learned how to use args and kwargs in Python programs. 

Recommended Reading-


Thanks for reading. I hope you found the blog insightful and that you have understood the use of args and kwargs in Python, and please upvote if you liked the article.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSand  System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy Learning!!

 

Previous article
Scope of Variable
Next article
Global Keyword in Python
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass