What does ** (double star/asterisk) and * (star/asterisk) do for parameters?


In Python, the * and ** symbols are used to denote special types of arguments when defining a function.

The * symbol is used to denote a variable-length argument list. This allows a function to accept any number of arguments, including zero. Here is an example:

def my_function(*args):
    # args is a tuple that contains all of the arguments passed to the function
    for arg in args:
        print(arg)

my_function(1, 2, 3)
# Output:
# 1
# 2
# 3

In this example, the * symbol is used to define a variable-length argument list named args. When the function is called, all of the arguments are collected into a tuple and assigned to args. This allows us to loop over the arguments and process them individually.

The ** symbol is similar to the * symbol, but it is used to denote a dictionary of keyword arguments. This allows a function to accept any number of named arguments, including zero. Here is an example:

def my_function(**kwargs):
    # kwargs is a dictionary that contains all of the keyword arguments passed to the function
    for key, value in kwargs.items():
        print(f"{key}: {value}")

my_function(arg1=1, arg2=2, arg3=3)
# Output:
# arg1: 1
# arg2: 2
# arg3: 3
In this example, the ** symbol is used to define a dictionary of keyword arguments named kwargs. When the function is called, all of the keyword arguments are collected into a dictionary and assigned to kwargs. This allows us to loop over the keyword arguments and process them individually.

The * and ** symbols can also be used when calling a function to unpack a list or dictionary of arguments. This allows you to pass a list or dictionary of arguments to a function without having to manually unpack the values. Here is an example:

def my_function(arg1, arg2, arg3):
    print(f"{arg1}, {arg2}, {arg3}")

my_list = [1, 2, 3]
my_function(*my_list)
# Output:
# 1, 2, 3

my_dict = {"arg1": 1, "arg2": 2, "arg3": 3}
my_function(**my_dict)
# Output:
# 1, 2, 3
In this example, we use the * symbol to unpack the values in my_list when calling my_function(). This is equivalent to calling my_function(1, 2, 3). Similarly, we use the ** symbol to unpack the values in my_dict when calling my_function(). This is equivalent to calling my_function(arg1=1, arg2=2, arg3=3).

Overall, the * and ** symbols are used to define and unpack variable-length argument lists and dictionaries of keyword arguments in Python. They are a convenient way to handle a variable number of arguments in a function definition or call.
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.