Before understanding what Python *args and Python **kwargs are, let us understand why there were created and what are their uses. In Python, we pass arguments to the user-defined functions in order to execute the operations in the function. Let us consider an example where we create a function for the addition of numbers. We pass 2 parameters to the function for adding numbers. The code is as follows:
def add(x,y):
print("Sum: ", x+y)
add(5, 10)
Output –
Sum: 15
Suppose we pass more than 2 parameters in the above program, will the program work? What will the output display?
def add(x,y):
print("Sum: ", x+y)
 add(5, 10, 15, 20)
Output –
TypeError: add() takes 2 positional arguments but 4 were given
What if we want to add 10 numbers using the same function? What if we want to pass a large number of data values as arguments to the function? We cannot always define the number of parameters in the function according to the values passed in the function. We cannot define 100 variables in the function if we have passed 100 values to the function for performing a mathematical operation.
In such cases, we take the help of special symbols pre-defined by Python which are known as *args and **kwargs. The args stands for arguments that are passed to the function whereas kwargs stands for keyword arguments which are passed along with the values into the function. We will learn about these special symbols in this article.
Definition
In order to solve the above-discussed issues, we use special symbols used for passing a variable number of arguments to a function.
In mathematical and programming language, we call these as Variadic functions i.e. one which accepts a variable number of arguments. Various programming languages support different variadic functions. Python programming language provides us with 2 variadic functions:
-
*args (Non-keyword Arguments/Positional Arguments) –
*args allows a function to accept any number of positional arguments i.e. arguments that are non-keyword arguments, variable-length argument list.
-
**kwargs (Keyword Arguments) –
**kwargs is a special syntax that allows us to pass a variable length of keyword arguments to the function.
Python *args
As we have seen the above programming issues arising due to number of arguments passing, Python has an *args which allows the user to pass a multiple number of arguments to the function. Python *args allows only Positional Arguments.
Note – Positional Arguments are those arguments that do not contain any keyword related to the data value. For example, age = 38. Age is a keyword associated with data value 38. In Python *args, we do not define any keywords to the arguments while passing values to the function.
- We use the single-asterisk (*) symbol for passing it as a parameter to the functions.
- args is just a word, we need to use the (*) symbol before it. We can use any alphabet/word instead of args.
- *args accepts all the parameters passed to the function and computes the function operations for each of them.
Let us look at few programming examples in order to understand the use of *args functionality.
Example 1 –
# Program to add and display the sum of n number of integer
def add(*num):
sum = 0;
for n in num:
sum = sum + n;
print("Sum:", sum)
add(2,6)
add(3,4,5,6,7)
add(1,2,3,5,6,7,8)
Output –
Sum: 8
Sum: 25
Sum: 32
In the above program, we do not face any issue of passing a variable number of arguments. The *num accepts all the parameters passed in the function add() and computes summation for all the values.
Example 2 –
# Program for printing all the strings passed to the function
def func(a,*args):
print("Value of a is:", a)
for i in args:
print(f' args are -> {i} ')
func('Hey', 'How', 'are', 'you?')
Output –
Value of a is: Hey
args are -> How
args are -> are
args are -> you?
Here, the ‘a’ parameter of the function is being assigned to the first argument ‘Hey’. The other arguments are assigned to the *args parameter.
Note – Python *args can also print data of various types which is passed into the function. For example, Information related to a person such as Name, Sex, Age, City, Mobile number, etc.
def Person(*args):
print(args)
Person('Sean', 'Male', 38, 'London', 9375821987)
Output –
('Sean', 'Male', 38, 'London', 9375821987)
Python **kwargs
One limitation of Python *args is that it does not accept any keyword arguments. Consider the above example, the program will print all the values passed to the function. But how will we identify what London is? Is it the city he lives in? Is it the work location? Is it a state? What is 38? Is it age, salary, person_id? For such an issue, Python has a special symbol called as **kwargs.
**kwargs allows us to pass a variable number of keyworded arguments to the function. Python *kwargs allows only Keyword Arguments.
- We use a double-asterisk (**) before the parameter name in the function argument.
- Just like args, kwargs is just another idiom, we can use any other name but we need to use the (**) symbol before it.
- Keyword arguments are like a dictionary, which maps the value to its associated key.
Example 1 –
# Print values of function Person along with its associated keywords
def Person(**kwargs):
for key, value in kwargs.items():
print("{} -> {}".format(key, value))Â Â Â # OR print(f'{key} -> {value}')
Person(Name = 'Sean', Sex = 'Male', Age = 38, City = 'London', Mobile = 9375821987)
Output –
Name -> Sean
Sex -> Male
Age -> 38
City -> London
Mobile -> 9375821987
In the above program, keywords Name, Sex, Age, City, Mobile gives more clarity of the data we have printed. This does not create any confusion and saves the users coding time. Hence, **kwargs use keywords associated with data values passed to the function.
We can use both the *args and **kwargs in a function together. But remember that *args need to be declared before **kwargs always.
Example –
def func(a, b, *args, option = False, **kwargs):
print(a, b)
  print(args)
  print(option)
  print(kwargs)
func(1, 3, 10, 20, Name = 'Tom', Salary = 60000)
Output –
1 3
(10, 20)
False
{'Name': 'Tom', 'Salary': 60000}
Practice Questions
Q1. Which of the following is not a type of argument in Python?
- Keyword
- Positional
- Default
- None of these
Answer. Option D
Q2. What will be the output of the following code?
def Person(*args):
   for i in args:
       print(i)
Person(name="Rachel", age="27")
- name Rachelage 27
- name = Rachel age = 27
- TypeError
- Rachel 27
Answer. Option C
Q3. What will be the output of the following program?
def Employee(**kwargs):
   for i in kwargs:
       print(i)
Employee(emp="Jim", salary=9000, age=34)
- emp salary age
- emp Jim salary 9000 age 34
- Jim 9000 34
- TypeError
Answer. Option A
Q4. *args is a special syntax used in python to pass variable-length keyword arguments to a function.
- True
- False
Answer. Option B
Q5. What will be the output of the following program?
def func(a, b, **kwargs, *args):
  print(a, b)
  print(args)
  print(kwargs)
func(1, 3, 10, 20, Name = 'Tom', Salary = 60000)
- 1 3 (10 20) {Name = Tom Salary = 60000}
- 1 3 Name = Tom Salary = 60000 10 20
- SyntaxError
- None of these
Answer. Option C
Leave a Reply