What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
In Python, the double star (**) is used to denote an "unpacking" operator, which allows you to unpack a dictionary or other iterable data type into keyword arguments in a function call.
In Python, the double star (**) is used to denote an "unpacking" operator, which allows you to unpack a dictionary or other iterable data type into keyword arguments in a function call. For example, consider the following function:
A simple function in Python
def greet(greeting, recipient):
return f"{greeting}, {recipient}!"
print(greet('Hello', 'World'))This function takes two arguments: greeting and recipient. If we have a dictionary that contains these values, we can "unpack" them into the function call like this:
Unpack a dictionary's values using a double asterisk and pass them to a function in Python
def greet(greeting, recipient):
return f"{greeting}, {recipient}!"
data = {'greeting': 'Hello', 'recipient': 'world'}
print(greet(**data))This would return the string "Hello, world!".
The single star (*) is used to unpack a sequence (such as a list or tuple) into individual positional arguments in a function call. For example:
Unpack a sequence into individual arguments in a function call in Python
def greet(greeting, recipient):
return f"{greeting}, {recipient}!"
args = ('Hello', 'World')
print(greet(*args))This would print the following:
Hello, World!Using * and ** in function definitions
While * and ** unpack arguments when calling a function, they pack arguments when defining a function. This allows functions to accept a variable number of arguments:
*argspacks extra positional arguments into a tuple.**kwargspacks extra keyword arguments into a dictionary.
For example:
def log(message, *args, **kwargs):
print(f"Message: {message}")
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
log("Start", "arg1", "arg2", key1="val1", key2="val2")This flexibility makes * and ** essential for writing adaptable Python functions.