What does ** (double asterisk) and * (single asterisk) do for parameters in Python?

0
0

In Python, the double asterisk (**) and single asterisk (*) operators have different meanings when used with function parameters.

The single asterisk (*) is used for unpacking iterable objects such as lists, tuples, and sets into separate arguments of a function. This is also known as “splatting”. Here’s an example:

def my_function(a, b, c):
print(a, b, c)

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

 

In this example, we define a function my_function that takes three arguments. We create a list my_list containing three elements, and then call my_function using the * operator to unpack the list and pass its elements as separate arguments to the function.

The double asterisk (**) is used for unpacking dictionaries into keyword arguments of a function. Here’s an example:

def my_function(a, b, c):
print(a, b, c)

my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
my_function(**my_dict)

 

In this example, we define a dictionary my_dict containing three key-value pairs. We call my_function using the ** operator to unpack the dictionary and pass its key-value pairs as keyword arguments to the function. The keys in the dictionary correspond to the parameter names in the function definition.

Both the * and ** operators can also be used in function parameter lists to accept a variable number of arguments. When used in this way, the * operator is used to accept a variable number of positional arguments, and the ** operator is used to accept a variable number of keyword arguments. Here’s an example:

def my_function(*args, **kwargs):
print(args)
print(kwargs)

my_function(1, 2, 3, a=4, b=5)

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.