Table of contents
1.
Introduction
2.
What are Arguments?
3.
Need of *args and **kwargs in Python
3.1.
Python
4.
What is *args in Python?
4.1.
Python
5.
What is **Kwargs in Python?
5.1.
Python
6.
Unpacking Arguments with *args and **kwargs in Python
6.1.
Python
7.
Pros and Cons of using args and kwargs in Python
7.1.
Pros
7.2.
Cons
8.
Difference between keyworded and non-keyworded arguments
9.
Using *args and **kwargs in Python to Call a Function
9.1.
Python
10.
Using *args and **kwargs to Set Values of an Object
10.1.
Python
11.
Frequently Asked Questions
11.1.
What is kwargs in Python?
11.2.
Is kwargs good practice?
11.3.
What does * mean in Python function arguments?
11.4.
How to pass kwargs to a function in Python?
12.
Conclusion
Last Updated: Nov 17, 2024
Easy

*Args and **Kwargs in Python

Author Rohit Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

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)

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)
You can also try this code with Online Python Compiler
Run Code

 

Output

15
You can also try this code with Online Python Compiler
Run Code

 

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")
You can also try this code with Online Python Compiler
Run Code

 

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")
You can also try this code with Online Python Compiler
Run Code

 

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))
You can also try this code with Online Python Compiler
Run Code

 

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.

Using *args and **kwargs in Python to Call a Function

  • *args and **kwargs are used to pass a variable number of arguments to a function.
  • *args allows passing a variable-length non-keyworded arguments (tuple).
  • **kwargs allows passing a variable-length keyworded arguments (dictionary).

Example:

  • Python

Python

def display_details(name, age, *args, **kwargs):
print(f"Name: {name}, Age: {age}")
print(f"Additional args: {args}")
print(f"Additional kwargs: {kwargs}")

display_details("Rohit", 30, "Engineer", "India", hobby="Reading", language="English")
You can also try this code with Online Python Compiler
Run Code

 

Output:

Name: Rohit, Age: 30  
Additional args: ('Engineer', 'India')  
Additional kwargs: {'hobby': 'Reading', 'language': 'English'}  

Using *args and **kwargs to Set Values of an Object

*args and **kwargs can be used in a class constructor or method to dynamically set object attributes.

Example:

  • Python

Python

class Person:
def __init__(self, *args, **kwargs):
# Assign positional arguments to predefined attributes
self.name = args[0] if len(args) > 0 else None
self.age = args[1] if len(args) > 1 else None

# Dynamically assign keyword arguments as attributes
for key, value in kwargs.items():
setattr(self, key, value)

# Create an object
person = Person("Rahul", 25, hobby="Cycling", city="Hyderabad")

print(person.name)
print(person.age)
print(person.hobby)
print(person.city)
You can also try this code with Online Python Compiler
Run Code

 

Output

Rahul
25
Cycling
Hyderabad

Frequently Asked Questions

What is kwargs in Python?

kwargs is a special syntax (**kwargs) in Python that collects variable-length keyword arguments into a dictionary for flexible function calls.

Is kwargs good practice?

kwargs is good practice for functions requiring dynamic arguments, but its overuse can reduce readability and make the code harder to debug.

What does * mean in Python function arguments?

* collects additional positional arguments into a tuple or separates positional arguments from keyword-only arguments when defining a function.

How to pass kwargs to a function in Python?

Pass kwargs by using ** before a dictionary when calling a function, allowing the dictionary keys to map to argument names.

def greet(name, age, city):
   print(f"Name: {name}, Age: {age}, City: {city}")

data = {"name": "Rahul", "age": 30, "city": "Banglore"}
greet(**data)  # Output: Name: Rahul, Age: 30, City: Banglore

Conclusion

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 Code360.

Live masterclass