*args
and **kwargs
are used in a function definition to allow for a variable number of arguments.
*args
is used to pass a variable number of non-keyword arguments to a function. The *
before args
tells Python to treat any additional arguments passed to the function as a tuple. Here's an example:
def my_function(*args): print(args) for arg in args: print(arg) my_function(1, 2, 3)
Click the run button above to see the output.
In this example, the my_function
can accept any number of arguments. The *args
parameter collects all the arguments passed to the function and stores them as a tuple. We then iterate over the args
tuple and print each argument.
One example of the built-in Python function that takes a variable number of arguments is the print
function.
print(1, 2) print(1, 2, 3)
On the other hand, **kwargs
is used to pass a variable number of keyword arguments to a function. The **
before kwargs
tells Python to treat any additional keyword arguments passed to the function as a dictionary. Here's an example:
def my_function(**kwargs): print(kwargs) for key, value in kwargs.items(): print(key, value) my_function(name="John", age=25) # Output: name John, age 25
In this example, the my_function
can accept any number of keyword arguments. The **kwargs
parameter collects all the keyword arguments passed to the function and stores them as a dictionary. We can then iterate over the kwargs
dictionary and print each key-value pair.
Both *args
and **kwargs
provide flexibility when working with functions that need to handle a variable number of arguments. They allow us to write functions that can accept different numbers of arguments without explicitly defining them in the function signature.
Note that *args
and **kwargs
are just naming conventions and can be replaced with any valid variable name. The *
and **
symbols are what make them special and indicate their purpose.