In Python, *args and **kwargs are some of the most common features that you will come across. *args and **kwargs in Python allow you to pass a variable number of arguments to functions. This makes your code a more flexible and adaptable version of what it could become without the arguments. You can learn to write efficient, reusable code by implementing these features and help you in working with functions dynamically. You will be given syntax, examples in this blog to help you in mastering their usage in Python.
Table of Contents:
What are *args in Python?
The working of *args in Python is explained as passing a variable number of non-keyword arguments to a function. The moment it is implemented, the function can be called with any possible number of arguments, without needing to define each one explicitly in the function signature and a separate manner. When you push *args in your function, all the extra positional arguments get stored in the tuple, which you can then use inside the function.
Syntax:
def function_name(*args):
Example:
Output:
Explanation: Here, the function print_numbers() will take an arbitrary number of arguments. These arguments will be passed to args as a tuple. Then the values get printed after the for loop iterates over every single element in the tuple. With the *args feature, you can attempt to pass any number of arguments you prefer to the function without needing to explicitly list them.
Advance Your Career with Python – Start Learning Now!!
Join thousands of learners building in-demand skills.
What are **kwargs in Python?
While *args is implemented for non-keyword arguments, the working of **kwargs is explained as passing a variable number of keyword arguments. Keep in mind that the arguments are passed with a key and a value. This feature is extremely useful when you need to handle arguments that are named dynamically. The function stores the dictionary that has collected the argument inside it. Here, the keys are the argument names and the values are the corresponding values.
Syntax:
def function_name( **kwargs):
Example:
Output:
Explanation: Here, this function print_details() will accept any number of keyword arguments. These arguments are passed to the kwargs dictionary. Then, the for loop iterates over the dictionary and prints each key-value pair. This demonstrates how **kwargs allows you to handle the named arguments flexibly.
Using Both *args and **kwargs together
The same function can have simultaneous implementation of both *args and **kwargs. However, there is a point where you need to remember that you need to follow certain rules while using both. In the function definition, make a note that *args always comes before **kwargs. Using both together permits you to accept both arbitrary positional and keyword arguments in a single function.
Syntax:
def function_name(*args, **kwargs):
Example:
Output:
Explanation: Here, the function display_info() can accept both positional and keyword arguments. The *args does the job of collecting positional arguments into a tuple, and **kwargs collects the keyword arguments into a dictionary. The function then prints both types of arguments separately. This approach allows you to work with both types of data in a single function.
Difference Between *args and **kwargs
Feature |
*args |
**kwargs |
Purpose |
Used for passing non-keyword arguments. |
Used for passing keyword arguments. |
Data Structure |
The arguments are stored in a tuple. |
The arguments are stored in a dictionary. |
Syntax |
It is prefixed with a single asterisk (* ). |
It is prefixed with two asterisks (** ). |
Use Case |
This is ideal for a function where the number of arguments is unknown. |
This is ideal for a function where the arguments are named or key-value pairs. |
Flexibility |
Allows passing any number of arguments of any type. |
Allows passing any number of named arguments. |
Use Cases for Implementing *args and **kwargs in Python
Use Case 1: Handling a Variable Number of Arguments with *args
You can use *args when writing functions that need to accept an unknown number of positional inputs.
Example:
Output:
Explanation: Here, any number of positional values can be accepted through *args when you code the function calculate_sum(). Inside the function, *args becomes a tuple: (22, 33, 44), which is then summed using the built-in function sum(). This flexibility allows the function to work regardless of the number of values passed.
Use Case 2: Passing Dynamic Settings to a Function using **kwargs
You can use **kwargs to allow functions to handle dynamic configuration or settings.
Example:
Output:
Explanation: Here, the setup_game() function receives a set of keyword arguments using **kwargs. These are stored in a dictionary internally and printed using a loop.
Get 100% Hike!
Master Most in Demand Skills Now!
Common Mistakes to Avoid while using *args and **kwargs
When using *args and **kwargs, there are a few common mistakes that can occur. Let us learn to avoid them:
Mistake 1: Implementing both *args and **kwargs in the wrong manner.
Always define *args before **kwargs in the function definition. Python will raise a SyntaxError as a direct result if you mix them up.
Mistake 2: Passing data that is not iterable to *args.
You will get an error if you try to pass a non-iterable value, as *args expects an iterable.
Mistake 3: Trying to overuse *args and **kwargs when the number of arguments is known.
While *args and **kwargs are both good in terms of flexibility, they can make the code harder to read if used without need. Only implement them when you need that level of flexibility.
Best Practices to Implement *args and **kwargs in Python
- Implement them only when there is a need: While we use *args and **kwargs to provide flexibility, they should be implemented only when you expect a variable number of arguments. If you know the number of arguments in advance, it’s better to define them explicitly.
- Keep the code readable: Make sure that when you are implementing *args and **kwargs, your function’s purpose is clear. You might have to reconsider the design if the function turns out to be too complicated to understand.
- Remember to use **kwargs for default values: If you’re passing a dictionary of options or configurations, **kwargs proves to be the most efficient and clear way to handle this. It allows you to set defaults and allows users to override them.
- Don’t use both in large functions: When functions start accepting a large number of arguments (whether positional or keyword), it may indicate that the function is doing too much. It’s better to refactor the function and break it down into smaller parts.
- Avoid combining *args and **kwargs with too many regular parameters: Doing so may confuse users about which arguments go where. Instead, use one style predominantly and document your function well.
Kickstart Your Coding Journey with Python – 100% Free
Beginner-friendly. No cost. Start now.
Conclusion
The *args and **kwargs are some of the very important features in Python that provide you with flexibility, reusability, and clean functions. When you understand how to implement them in your code, you can make your code efficient and adaptable. If you are stuck in dealing with dynamic outputs or passing some configurations, **kwargs, and *args allow your functions to deal with a wide range of circumstances with ease.
To take your skills to the next level, enrol in our Python training course and gain hands-on experience. Also, prepare for job interviews using our Python interview questions, designed by industry experts.
*args and **kwargs in Python – FAQs
Q1. Briefly explain the purpose of *args in Python.
*args lets a Python function take any number of values as input. It’s used when you don’t know how many arguments will be passed.
Q2. State the role of **kwargs in Python?
**kwargs allows a function to accept any number of keyword arguments. These arguments are stored in a dictionary, which lets you access the values using their corresponding keys.
Q3. Is it possible for a function to have both regular parameters, *args, and **kwargs?
Yes, a function can have regular parameters, which are followed by *args, and then **kwargs. This allows it to accept a combination of required, optional, and flexible keyword arguments.
Q4. Is the naming of *args and **kwargs mandatory?
No, the names args and kwargs are not mandatory, but it is a widely followed practice. What matters is the presence of the * and ** symbols, which tell Python how to handle the arguments.
Q5. Why is it necessary to use *args and **kwargs carefully?
You can easily create your functions to have more flexibility by introducing *args and **kwargs in your code, but you also need to make sure that you do not overuse these features, because they can easily ruin the readability and debugging of your code.