*args and **kwargs in Python
Last Updated :
11 Dec, 2024
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs.
Example:
Python
# *args example
def fun(*args):
return sum(args)
print(fun(1, 2, 3, 4))
print(fun(5, 10, 15))
# **kwargs example
def fun(**kwargs):
for k, val in kwargs.items():
print(k, val)
fun(a=1, b=2, c=3)
Let’s explore *args and **kwargs in detail:
There are two special symbols to pass multiple arguments:

*args and **kwargs in Python
Special Symbols Used for passing arguments in Python:
- *args (Non-Keyword Arguments)
- **kwargs (Keyword Arguments)
Note: “We use the “wildcard” or “*” notation like this – *args OR **kwargs – as our function’s argument when we have doubts about the number of arguments we should pass in a function.”
Python *args
The special syntax *args in function definitions is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.
- For example, we want to make a multiply function that takes any number of arguments and is able to multiply them all together. It can be done using *args.
- Using * the variable that we associate with the * becomes iterable, meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.
Example 1:
Python program to illustrate *args for a variable number of arguments
python
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
OutputHello
Welcome
to
GeeksforGeeks
Example 2:
Python program to illustrate *args with a first extra argument.
Python
def fun(arg1, *argv):
print("First argument :", arg1)
for arg in argv:
print("Argument *argv :", arg)
fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
OutputFirst argument : Hello
Argument *argv : Welcome
Argument *argv : to
Argument *argv : GeeksforGeeks
Python **kwargs
The special syntax **kwargs in function definitions is used to pass a variable length argument list. We use the name kwargs with the double star **.
- A keyword argument is where you provide a name to the variable as you pass it into the function.
- It collects all the additional keyword arguments passed to the function and stores them in a dictionary.
Example 1:
Python
def fun(**kwargs):
for k, val in kwargs.items():
print("%s == %s" % (k, val))
# Driver code
fun(s1='Geeks', s2='for', s3='Geeks')
Outputs1 == Geeks
s2 == for
s3 == Geeks
For s1=’Geeks’, s1 is key and ‘Geeks’ is a value. In simple words, what we assign is value and to whom we assign is key.
Example 2:
Python
def fun(arg1, **kwargs):
for k, val in kwargs.items():
print("%s == %s" % (k, val))
# Driver code
fun("Hi", s1='Geeks', s2='for', s3='Geeks')
Outputs1 == Geeks
s2 == for
s3 == Geeks
Using both *args and **kwargs
We can use both *args and **kwargs in the same function to accept a mix of positional and keyword arguments.
Example:
Python
def fun(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
fun(1, 2, 3, a=4, b=5)
OutputPositional arguments: (1, 2, 3)
Keyword arguments: {'a': 4, 'b': 5}
In this example, the fun can handle both positional and keyword arguments. The args parameter collects positional arguments into a tuple, while the kwargs parameter collects keyword arguments into a dictionary.
*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.
Difference between *args and **kwargs in Python?
*args collects additional positional arguments as a tuple, while **kwargs collects additional keyword arguments as a dictionary.
def example_function(*args, **kwargs):
print(args) # tuple of positional arguments
print(kwargs) # dictionary of keyword arguments
example_function(1, 2, 3, name='Alice', age=30)
Output:
(1, 2, 3)
{'name': 'Alice', 'age': 30}
Is *args a list or tuple in Python?
*args collects additional positional arguments into a tuple, not a list. The arguments are accessible using tuple indexing and iteration.
def example_function(*args):
print(type(args)) # <class 'tuple'>
example_function(1, 2, 3)
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.
Similar Reads
Python If Else Statements - Conditional Statements
In Python, If-Else is a fundamental conditional statement used for decision-making in programming. If...Else statement allows to execution of specific blocks of code depending on the condition is True or False. if Statementif statement is the most simple decision-making statement. If the condition e
4 min read
Loops in Python - For, While and Nested Loops
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read
Loops and Control Statements (continue, break and pass) in Python
Python supports two types of loops: for loops and while loops. Alongside these loops, Python provides control statements like continue, break, and pass to manage the flow of the loops efficiently. This article will explore these concepts in detail. Table of Content for Loopswhile LoopsControl Statem
2 min read
range() vs xrange() in Python
The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
2 min read
Iterators in Python
An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration. __iter__(): __iter_
3 min read
Iterator Functions in Python | Set 1
Perquisite: Iterators in PythonPython in its definition also allows some interesting and useful iterator functions for efficient looping and making execution of the code faster. There are many build-in iterators in the module "itertools". This module implements a number of iterator building blocks.
4 min read
Python __iter__() and __next__() | Converting an object into an iterator
In many cases, we may need to access an object in a way that treats it as if it were an iterator. This means we want to interact with the object in a manner similar to how we would with an iterator, enabling us to iterate over it or perform other iterable operations. For clarity, it's useful to say
6 min read
Python | Difference between iterable and iterator
Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Ever
3 min read
When to use yield instead of return in Python?
The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of v
2 min read